I have Offers table 2 row exit_customs and destination_customs. This 2 row has a my Customs table id. My problem is how to two(exit_customs and destination_customs) foreign key one(Customs) table?
Here is my list query function
router.post('/api/logistic/offers/get-offers', async (req, res) => {
const {limit, page, sortColumn, sortType, search} = req.body;
const total = await Offers.findAll();
const offersList = await Offers.findAll({
limit: limit,
offset: (page - 1) * limit,
order: [
[sortColumn, sortType]
],
where: {
[Op.or]:[
{
offers_no: {
[Op.substring]: [
search
]
}
},
{
agreement_date: {
[Op.substring]: [
search
]
}
},
{
routes: {
[Op.substring]: [
search
]
}
},
{
type_of_the_transport: {
[Op.substring]: [
search
]
}
},
]
}
});
res.json({
total: total.length,
data: offersList
});
})
this solution connects the two data in the first table to the id in the other table as you want. hope it helps
Offers.belongsTo(Customs, {as: 'Exit_customs', foreignKey: 'exit_customs'});
Offers.belongsTo(Customs, {as: 'Destination_customs', foreignKey: 'destination_customs'});
router.post('/api/logistic/offers/get-offers', async (req, res) => {
const {limit, page, sortColumn, sortType, search} = req.body;
const total = await Offers.findAll();
const offersList = await Offers.findAll({
limit: limit,
offset: (page - 1) * limit,
order: [
[sortColumn, sortType]
],
where: {
[Op.or]: [
{
offers_no: {
[Op.substring]: [
search
]
}
},
{
agreement_date: {
[Op.substring]: [
search
]
}
},
{
routes: {
[Op.substring]: [
search
]
}
},
{
type_of_the_transport: {
[Op.substring]: [
search
]
}
},
]
},
include: [{
model: Customs,
as: 'Exit_customs'
}, {
model: Customs,
as: 'Destination_customs'
}]
});
res.json({
total: total.length,
data: offersList
});
})
You can give foreign key using "as" keyword, please add below code in your Offers models file
static associate(models) {
models.Offers.belongsTo(models.Customs, {
foreignKey: "exit_customs",
as: "exitCustomsDetails",
});
models.Offers.belongsTo(models.Customs, {
foreignKey: "destination_customs",
as: "destinationCustomsDetails",
});
}
Related
I would like to know how can I "merge" the result to get result from 2 tables.
Currently I have 3 tables :
posts [id, title...]
feeds [id, fk_people_id, fk_post_id]
posts_peoples [id, fk_people_id, fk_post_id]
I would like to return the posts where people is present in feeds table and posts_peoples table.
When I run this request, I have only the post where people is present in feeds table :
// Request
const resultRequest = await db.Post.findAll({
include: [
{
model: db.Feed,
as: "Feed",
where: {
fk_people_id: 2,
},
},
],
})
When I run this request, I have only the post where people is present in posts_peoples table :
// Request
const resultRequest = await db.Post.findAll({
include: [
{
model: db.PostPeople,
as: "PostPeople",
where: {
fk_people_id: 2,
},
},
],
})
When I add feeds and posts_peoples, it doesn't work.
// Request
const resultRequest = await db.Post.findAll({
include: [
{
model: db.Feed,
as: "Feed",
where: {
fk_people_id: 2,
},
},
{
model: db.PostPeople,
as: "PostPeople",
where: {
fk_people_id: 2,
},
},
],
})
The result is an empty array.
Add required: false to your includes to generate SQL with a LEFT JOIN to include results from both tables.
// Request
const resultRequest = await db.Post.findAll({
include: [{
model: db.Feed,
as: "Feed",
where: {
fk_people_id: 2,
},
required: false,
},
{
model: db.PostPeople,
as: "PostPeople",
where: {
fk_people_id: 2,
},
required: false,
}],
})
Here is my code
const searchStringResult = (payload.match?.searchString);
const paginate = [
{
$facet: {
metadata: [{ $count: 'total' }],
data: [
{ $skip: payload.paginate?.skip || 0 },
{ $limit: payload.paginate?.limit || 10 },
],
},
},
{
$match: {
searchfields: {$regex: searchStringResult,$options: "-i"}
}
}
];
when I console log these code it doesn't show any error
but in console
[{"$facet":{"metadata":[{"$count":"total"}],"data":[{"$skip":0},{"$limit":10}]}},{"$match":{"searchfields":{"$regex":"a","$options":"-i"}}}]
I have a table with an associated table. I am using beforeDestroy to remove any associated records up deletion.
Model.beforeDestroy(async (category: any) => {
const items = await Category.findAll({
where: {
category_id: category.id,
},
attributes: ['id'],
raw: true,
});
console.log(items); // [ { id: 2 }, { id: 3364 }, { id: 3365 } ]
items.map((item: any) => {
Category.destroy({ where: { id: item.id } });
});
});
}
I am trying to delete the matching items with a single destroy query rather than mapping through.
try:
Category.destroy({ where: { id:items.map(item=>item.id)} });
How to write this sql query as sequelize query?
select * from chats where senderId + receiverId = 25
I want to use above query where condition in where clause of sequelize which is written below.
const options = {
page: req.params.pageNo, // Default 1
paginate: 25, // Default 25
order: [['id', 'DESC']],
include: [
{
model: db.users,
required: true,
as: 'senderUser',
attributes: ['id', 'name', 'email', 'mobileNumber', 'profilePic'],
},
{
model: db.users,
required: true,
as: 'receiverUser',
attributes: ['id', 'name', 'email', 'mobileNumber', 'profilePic'],
},
],
where: {
//here i need condition
},
};
db.chats
.paginate(options)
.then(result => {
let apiData = { pages: result.pages, total: result.total, chats: result.docs };
return _RL.apiResponseOk(res, 'Messages', apiData);
})
.catch(error => {
console.log(error);
return _RL.serverError(res);
});
You'll have to write aggregate query
await Chats.aggregate([
{
$addFields:{
'total':{$add:['$senderId','$receiverId']}
}
},
{
$match:{
'total':{$eq:25}
}
}
])
I'm assuming both senderId & receiverId are Numbers
I've this array.
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
path:'/disputes',
text: "Disputes"
},
{
children: [
{
text: "Create Suburb",
path: "/create-suburb"
},
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
{
children: [
{
text: "Create user",
path: "/create-user"
},
{
text: "View and Update users",
path: "/view-users"
}
]
}
]
and I've this array
const permissions = ['/dashboard','/view-suburb'];
What I want is filter out objects from the array where there is not in the permissions array.
My expected out put is this
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
children: [
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
]
Note that two objects are completely removed and some part of the third object also removed. How do I achieve this using JS?
What I've done upto now is this
items.filter(e=>{
if(e.path){
return permissions.includes(e.path)
}else{
}
})
Hope my question is clear to you.
You could do it with a reduce - filter alone won't work here as you're actually transforming child arrays rather than purely filtering the top level array items
routes.reduce((result, route) => {
const { path, children } = route;
if (children) {
const filteredChildren = children.filter(child => permissions.includes(child.path));
// case where some child routes match permissions
if (filteredChildren.length !== 0) {
return [ ...result, { ...route, children: filteredChildren }];
}
}
// case where path is present and permissions includes path
if (path && permissions.includes(path)) {
return [ ...result, route ];
}
// case where there's no match between path and permissions
return result;
}, []);
Try this!!
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
path:'/disputes',
text: "Disputes"
},
{
children: [
{
text: "Create Suburb",
path: "/create-suburb"
},
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
{
children: [
{
text: "Create user",
path: "/create-user"
},
{
text: "View and Update users",
path: "/view-users"
}
]
}
]
const permissions = ['/dashboard','/view-suburb'];
let result = [];
permissions.map(permission=>{
routes.map(route=>{
if(route.hasOwnProperty('children')){
route.children.map((r,i)=>{
if(r.path == permission){
route.children = route.children.splice(i);
route.children = route.children.slice(-1);
result.push(route)
}
});
}else{
if(route.path == permission){
result.push(route)
}
}
});
})
console.log(result)
This one also worked for me.
var newData = [];
$.each(routes, function (key, value) {
debugger
var data = this;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
else {
var data2 = data;
$.each(data2, function (key, value1) {
$.each(value1, function (key, value) {
var data = value;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
});
});
}
})
Ideally, you should check the access to the route inside the canActivate guard and navigate the user further to the appropriate route.