Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nine's avatar
Level 1

3 relations on pivot table

Hello,

I'm not sur of what kind of relation i put on my pivot table ?

I have to allow users tags/rates images according to one category , so I have 3 tables :

users images categories

plus, the pivot table with those foreign keys : user_id, image_id and category_id

So, My question is :

How find images untagged/unrated by user ?

Thank you!

0 likes
3 replies
Tray2's avatar

Something like

SELECT * 
FROM images
WHERE id NOT IN (SELECT image_id FROM pivot);

Should work

nine's avatar
Level 1

Thank you . Its what i do... But i m looking for an eloquent way Im not sure about what kind of relation i have to define in my models....

Tray2's avatar

It's not mandatory to use Eloquent everwhere. A simple query as the one I wrote can be very complicated in Eloquent. I usually use Eloquent for the easier more readable stuff and for the more complex I use raw SQL. If the query is really complex I might even create a view in the data base and then run eloquent against the view.

In your case it's the lack of relationship you want.

Something like this might be possible.

$images = Images::whereNotIn('id', Pivot::all());

Please or to participate in this conversation.