[英]Laravel: relationship between siblings
I have 4 tables flats
, residents
, floors
& resident_floors
.我有 4 桌
flats
、 residents
、 floors
和resident_floors
。 The relations between them is as follows:它们之间的关系如下:
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
I am trying to create the relationship between them to display the data as follows:我正在尝试创建它们之间的关系以显示数据,如下所示:
Flat / Floor(s) | Resident
1 / 101, 102 | Resident - 1
2 / 201 | Resident - 2
3 / 202 | Resident - 3
Resident.php居民.php
public function floors()
{
return $this->hasManyThrough(Floor::class, ResidentFloor::class, 'floors_id', 'id');
}
Here is the query which is being generated:这是正在生成的查询:
SELECT * FROM floors
INNER JOIN flat_resident_floors ON flat_resident_floors.id = floors.id
WHERE flat_resident_floors.floors_id = ?
Where as it should be:它应该在哪里:
SELECT * FROM floors
INNER JOIN flat_resident_floors ON flat_resident_floors.floors_id = floors.id
WHERE flat_resident_floors.residents_id = ?
I don't understand what or where am I doing wrong..?我不明白我做错了什么或在哪里做错了..?
Don't think about the underlying SQL so much, instead use the Eloquent relationships to your advantage.不要过多考虑底层的 SQL,而是使用 Eloquent 关系对您有利。 In this case, it seems that
Flat
should hasMany(Floor::class)
and Floor
should hasMany(Resident::class)
.在这种情况下,似乎
Flat
应该hasMany(Floor::class)
和Floor
应该hasMany(Resident::class)
。 Your Flat
then hasManyThrough
relationship with Resident
which writes itself (without needing a pivot table as you are trying to do).然后,您的
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.