简体   繁体   中英

Laravel: relationship between siblings

I have 4 tables 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

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. In this case, it seems that Flat should hasMany(Floor::class) and Floor should hasMany(Resident::class) . Your Flat then hasManyThrough relationship with Resident which writes itself (without needing a pivot table as you are trying to do).

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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