A
A
alexkst2020-10-07 15:41:02
MySQL
alexkst, 2020-10-07 15:41:02

Laravel hasOneThrough or belongsToMany. How to join three tables?

I'm trying to connect three tables, through intermediate ones.

There are such tables:

Apartments            - id - number
House                 - id - number
House_has_aparments   - id - house_id - apartment_id

Street                - id - name
Street_has_houses     - id - street_id - house_id


I'm trying to get complete information about the current apartment. Something like: Apartment 1 street name house number

This is for the house number
public function house()
    {
        return $this->belongsToMany(
            Houses::class,
            'houses_has_apartment',
            'apartment_id',
            'house_id',
            'id', 
            'id'
            );
    }


I then need to somehow get the street information using the house_id.
I did
public function street(){
        return $this->hasOne(Streets::class);
    }


and wanted to try this "$apartment->street->find(number)" and (obviously) it doesn't work.

Could you suggest me how to resolve this issue?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-10-07
@alexkst

One apartment cannot belong to several houses and vice versa.
Therefore,
house hasMany apartments
in apartments add house_id
Request and in the template $apartment->house->street
Apartment::with('house.street')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question