简体   繁体   English

Laravel Eloquent:检索“第二级”关系实体

[英]Laravel Eloquent: Retrieve “second level” relationship entity

I've 3 entity: 我有3个实体:

Owner
-id

Car
-id
-owner_id
-brand_id

Brand
-id

I would like to retrieve all brand of the cars of an owner . 我想检索所有brand的的cars的的owner

Now, if I do in the Owner class 现在,如果我在Owner类中

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

I receive a Database/Eloquent/Collection like this: 我收到这样的Database/Eloquent/Collection

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. 您可以在Owner模型上使用hasManyThrough关系。

For example: 例如:

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

There are two options to choose, 有两个选项可供选择,

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). 如果第二级表上没有外键(听起来不太好,但是可以使用),也可以使用belongsToMany。

Notice that, second parameter should be replaced with the name of Car table. 请注意,第二个参数应替换为Car表的名称。

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

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

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