Laravel Eager Loading, multiple same hasOne relati

2019-08-26 16:44发布

问题:

I have 2 simple models. First, one is called Builds and the second one is called SlotOptions. Each build can have like 5 assigned slots.

class BuildDB extends Model

And has 5 such relations slot1-5 and id changes to slot1-5_id

 public function slot1()
    {
        return $this->hasOne('\App\SlotOptions', 'id', 'slot1_id');
    }

In the controller I call it such way;

BuildDB::with([ 'slot1', 'slot2', 'slot3', 'slot4', 'slot5'])->find(5);

\App\SlotOptions model doesn't contain any extra coding.

This generates 5 "same" queries. - atm the eager loading would work if I get a list of builds and each slot would have whereIn clause, is it possible to have it a one big wherein the clause, or does it require to change the DB schema.

回答1:

It's not possible to optimize eager loading in this case.

I recommend that you change your database schema to a many-to-many relationship.
This design is more flexible, it allows you to easily add more slots in the future.

Create a pivot table named build_slot_option with these columns: build_id, slot_option_id
Add an additional column if you want to number/order the slots.

Then define a BelongsToMany relationship:

class BuildDB extends Model
{
    public function slots()
    {
        return $this->belongsToMany(
            SlotOptions::class, 'build_slot_option', 'build_id', 'slot_option_id'
        );
    }
}

BuildDB::with('slots')->find(5);