简体   繁体   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 has multiple objects how can I pass multiple objects to another query as shown below. $stores有多个对象,如何将多个对象传递给另一个查询,如下所示。 Need to match all id returned from Store model. 需要匹配Store模型返回的所有id Using first() returns only one object but in this case need to get all the stores and products related to those stores. 使用first()仅返回一个对象,但是在这种情况下,需要获取all商店和与这些商店相关的产品。

You can use whereIn() for that purpose. 您可以将whereIn()用于此目的。 Using your example as base: 以您的示例为基础:

$stores = $store::where('vendor_id', $id)->lists('id');
$products = Product::whereIn('store_id', $stores)->get();

I think you need something like this where $id is a given parameter or variable: 我认为您需要这样的东西,其中$id是给定的参数或变量:

$stores_id = Store::all()->where('vendor_id', $id)->lists('id');
$products = DB::table('products')->whereIn('id', $stores_id)->get();

This is assuming that you're using the default table names for the different models, that is products table name for the Product model. 假设您使用的是不同模型的默认表名,即Product模型的products表名。

The method lists($column_name) will return an array with the elements of the given column. 方法lists($column_name)将返回一个包含给定列元素的数组。 The whereIn($array) clause acts like the ÌN clause in SQL. whereIn($array)子句的行为类似于SQL中的ÌN子句。

NOTE: when using where you don't have to put the = sign, as Laravel will interpret it if you leave it blank. 注:当使用where你不必把=标志,因为如果你留空Laravel将它解释。

Assuming you have created your model relationship, you could do this. 假设您已创建模型关系,则可以执行此操作。

$stores = $store -> with('products') -> where('vendor_id',$id) ->first();

The query will fetch all products for the selected store. 该查询将获取所选商店的所有产品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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