1
我想在一個Model方法中合併兩個hasMany關係。這兩種關係幾乎完全相同,唯一的區別是外鍵。如何從同一個表中合併兩個hasMany關係?
請注意,我不能簡單地調用查詢構建器get()
兩種關係的方法,因爲我必須使用合併關係而不是集合,例如,我想稍後對合並關係進行排序,或者對其調用->where()
。
這裏是一個示例代碼:
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
}
}
根據定義,一個模型/表格只有一個標識符,它看起來好像Friend模型會有兩個標識符......甚至可能嗎? – Amarnasan
也許這是有幫助的:http://stackoverflow.com/questions/24184069/laravel-merge-reltationships – Amarnasan
@Amarnasan是我也發現了這個問題,但是這並沒有解決我的問題,因爲它在兩個集合合併爲一個單一集合意味着我無法再對其調用查詢方法。 – Zero