I want to merge two hasMany relations at one Model method. The two relations are nearly identical, the only difference is the foreign key.
Please note that I cannot simply call the query builders get()
Method on both relations because I have to work with the merged relation, not the collection, e.g. I want to sort the merged relation later, or call ->where()
on it.
Here is a sample code:
Friend.php
<?php
class Friend extends Model
{
/*
Database structure:
- id
- user_id
- friend_id
*/
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function friend()
{
return $this->belongsTo('App\Models\User', 'friend_id');
}
}
User.php
<?php
class User extends Model
{
/*
Database structure:
- id
[...]
*/
public function friends()
{
$friends_left = $this->hasMany('App\Models\Friend', 'friend_id');
$friends_right = $this->hasMany('App\Models\Friend', 'user_id');
// return single relation
}
}