Laravel Many to many self referencing table only works one way

后端 未结 2 1329
灰色年华
灰色年华 2020-12-03 03:55

I have set up the relationship and the models as below:

pivot table schema

Schema::create(\'friend_user\', function(Blueprint $table) {
    $table-&g         


        
相关标签:
2条回答
  • 2020-12-03 04:13

    use this

    public function friends()
    {
     return $this->belongsToMany('User', 'friend_user', 'user_id', 'friend_id')->orWhere('friend_id', $this->id);;
    }
    

    in this case you get one query and one record for each relation

    0 讨论(0)
  • 2020-12-03 04:30

    Instead of creating two records use a new function.

    public function friends()
    {
      return $this->belongsToMany('User', 'friend_user', 'user_id', 'friend_id');
    }
    
    // Same table, self referencing, but change the key order
    public function theFriends()
    {
      return $this->belongsToMany('User', 'friend_user', 'friend_id', 'user_id');
    }
    
    //You can then call opposite record(s) using:
    foreach( Auth::user()->theFriends as $theFriends )
    

    I used this approach in my project so I can have better separation for organizing the results.

    0 讨论(0)
提交回复
热议问题