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