laravel orm : where condition on table -> related table -> related table

倾然丶 夕夏残阳落幕 提交于 2021-02-19 07:54:25

问题


so here is my database for a book store

books : id ,title 
category : id,  title 

book_category : id , book_id,  category_id 
book_stock : id , book_id , quantity , price 

considering all the relations are defined in the model , i can query book_stock it goes something like this

Stock::with('Book')->get();

but what if i want to get stock of a book in the category = 1

i can use use condition on book

Stock::with('Book' , function($q){
   $q->where(['title'=>'abc']);
})->get();

but how can i filter related table of book ? basically i want to get book_id from book_category where category_id = 1 and then use those ids to filter my books finally get stock

ps : i don't want to use query builder


回答1:


You can do:

Stock::with('Book.stock', 'Book.category')->get();

You can access any number of nested relations within a with statement.


Related question:

Laravel nested relationships


Armin Sam's answer should also be a viable option.




回答2:


This will return you all books belonging to category=1 with their stock information:

$categoryId = 1;

$books = Book::with('stock')->whereHas('category', function($query) use ($categoryId) {
    return $query->where('id', $categoryId);
})->get();


来源:https://stackoverflow.com/questions/40304134/laravel-orm-where-condition-on-table-related-table-related-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!