繁体   English   中英

如何将多个对象传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM