本文介紹了Laravel 查詢多對多的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我需要幫助.我有 2 個表 products
和 categories
:
I need help.I have 2 tables products
and categories
:
獲取請求發送類別 ID.我的問題是:如何使用產品模型構建查詢???(查詢看起來像這樣:輸出類別 id 等于 $ request-> category 的產品).表連接配置好了,我只需要查詢,(我看了文檔,但沒看懂)
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)
推薦答案
您可以使用:
$products = Product::whereHas('categories', function($q) use ($categoryId) {
$q->where('id', $categoryId);
})->get();
閱讀查詢關系
當然你需要配置Product
模型和categories
關系.
Of course you need to have configured Product
model with categories
relationship.
這篇關于Laravel 查詢多對多的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!