I have model answerlist which has ownerId and answeredBy objects containing ownerId.
I want to fetch answerlist's data where ownerId = answeredBy.ownerId.
Don't know how to do it in sequelize.
Following is my code
db.answersList.findAll({
include: [
{ model: db.Employee, as: 'answeredBy', attributes: ['id', 'ownerId']},
{ model: db.Owner, as: 'owner',attributes: ['id']}
],
want to do something like where:{'answeredBy.ownerId':'owner.id'}
});
Related
I'm trying to use the distinct clause to filter out some rows from a query. I have two models called Parcel and DeliveryProblem. Each parcel can have n delivery problems and I must get a list of Parcels through the DeliveryProblem side of the relation.
Obviously this causes the result to have many duplicated Parcels which I'd like to filter out. This is what I have tried using:
const problems = await DeliveryProblem.findAll({
limit: 20,
offset: (page - 1) * 20,
attributes: ['parcel_id', 'id'],
include: [
{
model: Parcel,
as: 'parcel',
distinct: ['parcel_id']
attributes: ['product', 'start_date'],
include: [
{
model: Deliveryman,
as: 'deliveryman',
attributes: ['name'],
},
],
},
],
});
It seems sequelize simply ignores the distinct property and keeps returning me the full set. Is there any other way to achieve the distinct set of rows?
You can use the distinct option with count and aggregate functions only.
I'm using sequelize to handle SQLite database used by Electon app. Application let the user search for music based on selected topics, moods and so on.
I'm trying to build search mechanism that allow to select multiple moods and the function should return tracks that have all of the selected moods
Here is mentioned above database simplified model:
Also the sequelize relation between models are set
db.moods.belongsToMany(db.tracks, {
through: db.moodsTracks,
foreignKey: 'uuid',
});
db.tracks.belongsToMany(db.moods, {
through: db.moodsTracks,
foreignKey: 'trackId',
});
db.moods.hasMany(db.moodsTracks, {foreignKey: 'uuid'});
db.tracks.hasMany(db.moodsTracks, {foreignKey: 'trackId'});
Now I'm trying to find all tracks that contain has specific moods
let tracks = await db.tracks.findAll({
include: [{
model: db.moods,
required: true,
where: uuid: {
[Op.and]: ['MOOD-UUID-1', 'MOOD-UUID-2']
}
}],
})
(first try fail)
I have tried to log generated by sequelize code and its returns:
INNER JOIN `moodsTracks` AS `moodsTracks` ON `tracks`.`id` = `moodsTracks`.`trackId`
AND (
`moodsTracks`.`uuid` = 'MOOD-UUID-1'
AND `moodsTracks`.`uuid` = 'MOOD-UUID-2'
)
Then I have try to build raw SQLite query
SELECT
COUNT(trackid),
*
FROM
`tracks` AS `tracks`
INNER JOIN `moodstracks` AS `moodsTracks` ON `tracks`.`id` = `moodstracks`.`trackid`
WHERE
(
`moodsTracks`.`uuid` = 'MOOD-UUID-1'
OR `moodsTracks`.`uuid` = 'MOOD-UUID-2'
)
GROUP BY
(`moodsTracks`.`trackId`)
HAVING
COUNT(trackid) = 2;
I'm aware that isn't great solution, but it works in SQL console.
Questions:
Is there any other way to solve that kind problem? Maybe I use AND operator wrongly
If not, I will try to implement that SQL code above.
Is there any documentation for HAVING keyword in sequelize, i didn't found any thing like this on official web page
Why are you using [Op.and] when in your raw query you are using 'OR'?
This solution works for me:
let tracks = await db.tracks.findAll({
include: [db.moods],
group: 'moodsTracks.trackId',
include: [{
model: db.moods,
where: {
uuid:['UUID1', 'UUID2']
},
having: ["COUNT(DISTINCT moodsTracks.uuid) = 2"]
}]
})
I have a model Booking, which is having hasMany relation with hotels, and hotel is having one to one relation with supppliers.
What i need is, get all booking where supplier_id = 33333.
I am trying this
BOOKINGS.findAll({
where: {
'hotels.supplier.supplier_id' : '32',
},
include: [
{
model: HOTELS,
include: [
{
model: SUPPLIERS,
],
}
],
limit : 30,
offset: 0
})
It throws error like hotels.supplier... column not found.. I tried all things because on docs of sequelze it only gives solution to add check which adds where inside the include which i can't use as it adds sub queries.
I don't want to add where check alongwith supplier model inside the include array, because it adds sub queries, so If i am having 1000 bookings then for all bookings it will add sub query which crashes my apis.
I need a solutions like this query in Sequelize.
Select col1,col2,col3 from BOOKINGS let join HOTELS on BOOKINGS.booking_id = HOTELS.booking_id, inner join SUPPLIERS on BOOKINGS.supplier_id = SUPPLIERS.supplier_id
Adding a where in the include object will not add a sub query. It will just add a where clause to the JOIN which is being applied to the supplier model. It will not crash your API in anyway. You can test it out on your local machine plenty of times to make sure.
BOOKINGS.findAll({
include: [
{
model: HOTELS,
include: [
{
model: SUPPLIERS,
where: { supplier_id: 32 }
}
]
}
],
limit: 30,
offset: 0
})
If you still want to use the query on the top level you can use sequelize.where+ sequelize.literal but you will need to use the table aliases that sequelize assigns. e.g this alias for supplier table will not work hotels.supplier.supplier_id. Sequelize assings table aliases like in the example I have shown below:
BOOKINGS.findAll({
where: sequelize.where(sequelize.literal("`hotels->suppliers`.supplier_id = 32")),
include: [
{
model: HOTELS,
include: [SUPPLIERS]
}
],
limit: 30,
offset: 0
})
I have two models, named users and messages. It's basically a chat application. The models are associated as below:
User.hasMany(Message);
Message.belongsTo(User);
User-> id, name, pic
Message-> id, text, timestamp, user_id (foreign key)
I want to get a list of users who has recently messaged. Here is what I've tried:
DB.User.findAll({
include: [{
model: DB.Message,
order: [
['timestamp', 'DESC']
],
limit: 1
}]
});
The SQL Query may look like this:
SELECT U.first_name, user_id, MAX(timestamp) FROM messages M, users
U WHERE M.user_id=U.id GROUP BY user_id
Try this
DB.User.findAll({
include: [ { model: DB.Message, required: true,order:['id','DESC']}]
});
I'm currently working on a project where I have 3 models with a child and parent structure.
City has multiple Locations which has multiple Stones. Each Stone only has one Location as parent and each Location only has one City as parent.
Now, I want to create a list of all Stones that 'belong' (through a Location) to a specific City. How would I retrieve all these associations, without having to do the following:
City.find({
where: {
id: 1337
},
include: [{
model: Location,
include: [{
model: Stone
}]
}]
})
.then((city) => {
city.stones = [].concat.apply([], city.locations.map(location => location.stones));
});
I'm trying to find out if there's a "SQL only" solution, so not retrieving data / having to execute JavaScript to generate this array.