Laravel:兄弟姐妹之间的关系

时间:2019-10-02 12:05:02

标签: laravel model relationship

我有4个表flatsresidentsfloorsresident_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

Resident.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 = ?

我不知道我在做什么或在哪里做错..?

1 个答案:

答案 0 :(得分:0)

不要过多地考虑基础SQL,而要使用Eloquent关系来发挥自己的优势。在这种情况下,似乎Flat应该hasMany(Floor::class)Floor应该hasMany(Resident::class)。您与Flat的{​​{1}}然后是hasManyThrough关系,该关系会自动进行写入(无需尝试使用数据透视表)。

Resident