本文介紹了Laravel 獲取一組關系項的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我被困在這個看似簡單的任務上.
I'm stuck on this what seems like a simple task.
我有一個用戶有很多商店,有很多產品..
我正在嘗試獲取某個用戶的所有產品.
I'm trying to get all the Products for a certain User.
這是有效的,并且正在返回商店及其產品
This is working, and is returning the Shops with their Products
Auth::user()->shops()->with('products')->get();
但我只需要產品的集合.我嘗試了以下但它搞亂了查詢
But I need a Collection of only the Products. I tried the following but it's messing up the Query
Auth::user()->shops()->with('products')->select('products.*')->get();
知道我做錯了什么嗎?謝謝!
Any idea what I'm doing wrong? Thank you!
推薦答案
你可以使用這個:
Auth::user()->shops()->with('products')->get()->pluck('products')->flatten();
如果你不想復制,你可以使用->unique()
if you don't want replicate, you can use ->unique()
如果您想直接處理查詢(用于表演):
If you want to directly work on a query (for performances):
Product::whereHas('shops', function($query){
$query->where('user_id', auth()->user()->id);
})->get();
這篇關于Laravel 獲取一組關系項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!