[英]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.