![](/img/trans.png)
[英]How to add a meta field to a collection of Eloquent model objects in Laravel
[英]How to pass multiple objects to laravel eloquent model
$stores = $store->where('vendor_id', '=', $id)->get();
$products = Product::where('store_id', '=', $stores->id)->get();
$stores
有多個對象,如何將多個對象傳遞給另一個查詢,如下所示。 需要匹配Store
模型返回的所有id
。 使用first()
僅返回一個對象,但是在這種情況下,需要獲取all
商店和與這些商店相關的產品。
您可以將whereIn()
用於此目的。 以您的示例為基礎:
$stores = $store::where('vendor_id', $id)->lists('id');
$products = Product::whereIn('store_id', $stores)->get();
我認為您需要這樣的東西,其中$id
是給定的參數或變量:
$stores_id = Store::all()->where('vendor_id', $id)->lists('id');
$products = DB::table('products')->whereIn('id', $stores_id)->get();
假設您使用的是不同模型的默認表名,即Product
模型的products
表名。
方法lists($column_name)
將返回一個包含給定列元素的數組。 whereIn($array)
子句的行為類似於SQL中的ÌN
子句。
注:當使用where
你不必把=
標志,因為如果你留空Laravel將它解釋。
假設您已創建模型關系,則可以執行此操作。
$stores = $store -> with('products') -> where('vendor_id',$id) ->first();
該查詢將獲取所選商店的所有產品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.