Laravel query many to Many

断了今生、忘了曾经 提交于 2020-02-05 08:21:30

问题


I need help.I have 2 tables products and categories:

Get request sends category id. My question is: how to build a query using the product model??? (The query looks like this: Output the product where the category id is equal to $ request-> category). Table connections are configured, I only need the query, (I read the documentation, but do not not understand it)


回答1:


You can use:

$products = Product::whereHas('categories', function($q) use ($categoryId) {
   $q->where('id', $categoryId);
})->get();

Read about querying relationships

Of course you need to have configured Product model with categories relationship.




回答2:


You've said it's many-to-many relationship, all relations are configured and you want to use Product model to build a query. In this case, you should use the whereHas() method:

Product::whereHas('categories', function($q) use($request) {
    $q->where('id', $request->category);
}))->get();


来源:https://stackoverflow.com/questions/47979922/laravel-query-many-to-many

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