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

inyansuta's avatar

Relation query with dynamic parent condition

I have two tables.

catalogs - id | name
photos - id | photoable_id | photoable_type

When I need all catalogs with photos, is simple, all works:

$catalogs = Catalog::with('photos');

But every Catalog can have main photo, in catalog table I have too aditional column main_photo_id (id into photos table or can be nullable...).

How can I make query for Catalogs with photos, but without the main photos?

When I try something like this, don't work...

$catalogs = Catalog::with('photos')->whereHas('photos', function($query) {
            $query->where('photos.id', '!=', 'catalog.main_photo_id');
        })->first();

// or

$catalogs = Catalog::with(['photos' => function($query) {
            $query->where('photos.id', '!=', 'catalog.main_photo_id');
        }])->first();

Thank you for your help.

0 likes
3 replies
ekhlas's avatar

try this

$catalogs = Catalog::with('photos')->where('photos.id', '<>', 'catalog.main_photo_id')->first();
inyansuta's avatar

@ekhlas This can't work... Column not found: 1054 Unknown column 'photos.id' in 'where clause' (SQL: select * from catalogs where photos.id <> catalogs.main_photo_id)

Please or to participate in this conversation.