[英]Laravel How to handle One To Many relationship using Pivot Tables
我有一個新的 Laravel 應用程序,我正在連接到一個預先存在的數據庫。 這個數據庫中的關系幾乎都是數據透視表。
與此類似:
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('vehicles', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('customer_vehicle', function (Blueprint $table) {
$table->id();
$table->int('customer_id');
$table->int('vehicle_id');
});
我已經配置了模型/數據透視表並為客戶和車輛建立了多對多關系。
與此類似:
class Customer extends Model
{
public function vehicles()
{
return $this->belongsToMany(
Vehicle::class,
CustomerVehiclePivot::class,
'customer_id',
'vehicle_id'
);
}
}
class Vehicle extends Model
{
public function customers()
{
return $this->belongsToMany(
Customer::class,
CustomerVehiclePivot::class,
'vehicle_id',
'customer_id'
);
}
}
到目前為止,這是可行的,但感覺不太對勁。 $customer->vehicles()
返回預期結果,但車輛應該只屬於一個客戶,我現在這樣做的方式是$vehicle->customers()->first()
。
實際關系應該是一對多。 一個客戶可以擁有多輛車,但一輛車應該只屬於一個客戶。
有沒有辦法在使用數據透視表時將關系配置為一對多關系,以便能夠使用$vehicle->customer
獲取車輛的客戶?
根據@chuck 的建議,我的 Vehicle 客戶方法現在有以下內容。
class Vehicle extends Model
{
public function customer()
{
return $this->hasOneThrough(
Customer::class,
CustomerVehiclePivot::class,
'vehicle_id',
'id',
'id',
'customer_id'
);
}
}
我現在可以執行以下操作並獲得預期的結果。
$vehicle->customer; // Returns the vehicle's customer
$customer->vehicles; // Returns the customer's vehicles
我現在正試圖弄清楚如何使用具有這種配置的工廠。
我以為我可以做Vehicle::factory()->for(Customer::factory())->create()
但我收到錯誤...
調用未定義的方法 Illuminate\Database\Eloquent\Relations\HasOneThrough::getOwnerKeyName()
所以我不太確定如何為用戶創建車輛。
通過使用hasAttached
,我成功地創建了帶有附加車輛的用戶。
Customer::factory()
->hasAttached(
Vehicle::factory()->count(3)
)
->create()
我能夠弄清楚如何使用工廠為用戶制造車輛。
Customer::factory()->create()->vehicles()->attach(Vehicle::factory()->count(3)->create());
是的,您可以使用 Laravel 中的 hasOneThrough() 關系,使用數據透視表在客戶和車輛之間建立一對多關系。 以下是如何設置的示例:
class Customer extends Model
{
public function vehicles()
{
return $this->hasMany(Vehicle::class);
}
}
class Vehicle extends Model
{
public function customer()
{
return $this->hasOneThrough(
Customer::class,
CustomerVehiclePivot::class,
'vehicle_id', // Foreign key on the pivot table
'id', // Local key on the customers table
'id', // Local key on the vehicles table
'customer_id' // Foreign key on the pivot table
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.