繁体   English   中英

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

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

我有3个实体:

Owner
-id

Car
-id
-owner_id
-brand_id

Brand
-id

我想检索所有brand的的cars的的owner

现在,如果我在Owner类中

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

我收到这样的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
            },
        },
    ],
}

但是我想要一个这样的结构:

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

有可能吗?

您可以在Owner模型上使用hasManyThrough关系。

例如:

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

有两个选项可供选择,

简单示例(您可能需要将列名设置为参数。);

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

如果第二级表上没有外键(听起来不太好,但是可以使用),也可以使用belongsToMany。

请注意,第二个参数应替换为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