繁体   English   中英

Laravel:兄弟姐妹之间的关系

[英]Laravel: relationship between siblings

我有 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

居民.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) 然后,您的FlatResident具有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM