簡體   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