[英]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.