简体   繁体   中英

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. Need to match all id returned from Store model. Using first() returns only one object but in this case need to get all the stores and products related to those stores.

You can use whereIn() for that purpose. 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:

$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.

The method lists($column_name) will return an array with the elements of the given column. The whereIn($array) clause acts like the ÌN clause in SQL.

NOTE: when using where you don't have to put the = sign, as Laravel will interpret it if you leave it blank.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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