R
R
Roman2019-02-23 00:11:33
Laravel
Roman, 2019-02-23 00:11:33

How to make a many-to-many relationship of a model to itself in Laravel?

Hello.
I want, for example, to make the "Add to friends" option, and for this I need a many-to-many relationship in the User model, but to myself, right?
What is usually done in such cases?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2019-02-23
@procode

We do hasMany with User on the user's friends table

public function friends(){
        return $this->hasMany('App\Models\Friend, 'user_id', 'id');
    }

Make 2 ids in this table:
Who adds to friends (Auth:id()) field user_id
Whom the user adds to friends - field friend_id
As a result, using the create method, we make an entry when adding to friends. If the user is added as a friend, the same is true.
we get
$user->friends()->get()
$user->friends()->find($id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question