简体   繁体   中英

Laravel Eloquent ORM find related object

What is the correct way to find a related object based on a where clause with Eloquent ORM?

For example, I want to find a specific Product object that is related to a Store object. I thought I could do something like this:

$store = Store::where('hash', Input::get('s'))->first();
$product = $store->products->where('ext_id', 2)->get();

However, I'm getting an error that where is an unknown method. If instead of where I use find , that works correctly:

$product = $store->products->find(1);

Why can't I use where this way?

$product = $store
    ->products()
    ->where('ext_id', 2)->get();

This will not run 2 queries.

The difference is this:

$store->products() // relation object you can query
$store->products // already fetched related collection / model (depending on relation type)

Also you can use eager loading:

$store =  Store::where('hash', Input::get('s'))
    ->with(['products' => function ($q) {
        $q->where('ext_id', 2);
    }])->first();

This will load only ext_id = 2 products on the store, that will be accessible via $store->products


Now, there are different methods find involved:

$store->products()->find(1); // runs select ... where id=1
$store->products->find(1); // gets model with id 1 from the collection

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