简体   繁体   中英

Laravel Eloquent: Retrieve “second level” relationship entity

I've 3 entity:

Owner
-id

Car
-id
-owner_id
-brand_id

Brand
-id

I would like to retrieve all brand of the cars of an owner .

Now, if I do in the Owner class

$this->cars()->with('brand');

I receive a Database/Eloquent/Collection like this:

Illuminate\Database\Eloquent\Collection {
    all: [
        App\Car {
            id: 1,
            owner_id: 10,
            brand_id: 100,
            brand: App\Brand {
                id: 100
            },
        },
        App\Car {
            id: 2,
            owner_id: 10,
            brand_id: 200,
            brand: App\Brand {
                id: 200
            },
        },
        App\Car {
            id: 3,
            owner_id: 10,
            brand_id: 100,
            brand: App\Brand {
                id: 100
            },
        },
    ],
}

but I would like to have a structure like this:

Illuminate\Database\Eloquent\Collection {
    all: [
        App\Brand {
            id: 100
        },
        App\Brand {
            id: 200
        },
}

Is it possible in some way?

You can use the hasManyThrough relationship on the Owner model.

For example:

public function brands()
{
    return $this->hasManyThrough(Brand::class, Car::class);
}

There are two options to choose,

  • You may use features of Eloquent Collections and filter/map your object to convert it to the form you want.
  • You can define another relation on your model using hasManyThrough .

Simple example (you may required to set column names as a parameter.);

public function brands() { 
     return $this->hasManyThrough(Brand::class, Car::class);
}

Also you may use belongsToMany, if you don't have foreign key on your second level table (it doesn't sound well, but it works).

Notice that, second parameter should be replaced with the name of Car table.

public function brands(){
    return $this->belongsToMany(Brand::class, 'cars', 'owner_id', 'brand_id');
}

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