rajkumar_zuan's avatar

Foreign key in front

Here I've relationship for getting items from category. but when I check laravel debugger query, it shows where condition in first and then relationship in last, if I add multiple where conditions, foreign_key loading after all the where conditions, how to set foreign_key in first public function items(){ return $this->hasMany(\App\Items::class, 'category_id', 'id')->where(['items.available'=>1]); }

select * from items where (items.available = 1) and items.category_id in (633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 728, 729, 730, 885) and items.deleted_at is null

0 likes
4 replies
vincent15000's avatar

What is your question ? I don't see any real problem arount the query.

rajkumar_zuan's avatar

there is no problem sir, Query works fine, but my question is, why foreign key loading in last of the Query, If I add multiple where conditions in relationship, all the where condition in SQL query loads 1st and finally foreign key loads in last.

Eg: public function items(){ return $this->hasMany(\App\Items::class, 'category_id', 'id')->where(['items.available'=>1])->where(['items.parent'=>NULL]); }

In above relationship 'category_id' is foreign key, and I've added where ( items.available = 1), and (items.parent = null)

select * from items where (items.available = 1) and (items.parent = null) and items.category_id in (633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 728, 729, 730, 885) and items.deleted_at is null

relationship executed like above Query,

I'm expecting like below,

select * from items items.category_id in (633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 728, 729, 730, 885) and where (items.available = 1) and where (items.parent = NULL) and items.deleted_at is null.

how do I loads where condition after foreign_key

1 like
kokoshneta's avatar

@rajkumar_zuan The query you say you expect is not valid SQL at all. There's no AND WHERE in SQL (and the first WHERE is missing altogether).

There’s also no point whatsoever in nesting your WHERE conditions by putting them inside arrays.

And as Vincent says, it doesn’t matter what order your WHERE conditions are given in. You can reorder them any way you want and get the same result. Eloquent presumably orders them based on some sort of internal logic that you can’t control, but it really doesn’t matter.

Please or to participate in this conversation.