M
M
Mikhail2021-01-04 17:41:44
Laravel
Mikhail, 2021-01-04 17:41:44

What relation to apply for 4 tables?

There are 4 tables:
Homes (id name)
Users (id name)
Home_Users (user_id home_id)
Phones (user_id home_id phone)

A user can have multiple homes
A user can have only one phone for one home

User's home via belongsToMany
belongsToMany(Home: :class, 'users_homes')
Everything is ok. I bind $user->homes()->attach($home);

But how to bind the phone now and which method to use?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-01-04
@New_Horizons

make the user have the relationship "phones" hasMany, then:

$user->phones()->save(new Phone(['home_id' => $home->id, 'phone' => '+79999999999']));

or like this:
Phone::create(['user_id' => $user->id, 'home_id' => $home->id, 'phone' => '+79999999999']);

The only thing I don't know is whether this will work with a composite key. In any case, I advise you to make a regular id key for phones, because eloquent does not support composite keys (out of the box and without crutches)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question