[英]Laravel: relationship between siblings
我有 4 桌flats
、 residents
、 floors
和resident_floors
。 它們之間的關系如下:
flats:
id | name
-----------------------------
1 | Flat -1
2 | Flat -2
...
flat_residents:
id | flats_id | name
-----------------------------
1 | 1 | Resident - 1
2 | 2 | Resident - 2
3 | 3 | Resident - 3
...
flat_floors:
id | flats_id
-----------------------------
1 | 101
2 | 102
3 | 201
4 | 202
...
flat_resident_floors:
id | residents_id | floors_id
-----------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 3 | 4
我正在嘗試創建它們之間的關系以顯示數據,如下所示:
Flat / Floor(s) | Resident
1 / 101, 102 | Resident - 1
2 / 201 | Resident - 2
3 / 202 | Resident - 3
居民.php
public function floors()
{
return $this->hasManyThrough(Floor::class, ResidentFloor::class, 'floors_id', 'id');
}
這是正在生成的查詢:
SELECT * FROM floors
INNER JOIN flat_resident_floors ON flat_resident_floors.id = floors.id
WHERE flat_resident_floors.floors_id = ?
它應該在哪里:
SELECT * FROM floors
INNER JOIN flat_resident_floors ON flat_resident_floors.floors_id = floors.id
WHERE flat_resident_floors.residents_id = ?
我不明白我做錯了什么或在哪里做錯了..?
不要過多考慮底層的 SQL,而是使用 Eloquent 關系對您有利。 在這種情況下,似乎Flat
應該hasMany(Floor::class)
和Floor
應該hasMany(Resident::class)
。 然后,您的Flat
與Resident
具有hasManyThrough
關系,它自己寫入(不需要 pivot 表,因為您正在嘗試這樣做)。
class Floor
{
public function residents()
{
return $this->hasMany(Resident::class);
}
public function flat()
{
return $this->belongsTo(Flat::class);
}
}
class Resident
{
public function floor()
{
return $this->belongsTo(Floor::class);
}
}
class Flat
{
public function floors()
{
return $this->hasMany(Floor::class);
}
public function residents()
{
return $this->hasManyThrough(Resident::class, Floor::class);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.