这些是我的表格:
用户:
id username password
1 user1 ********
2 user2 ********
3 user3 ********
4 user4 ********
5 user5 ********
6 user6 ********
UserConnections :
pivot_id parent_user_id child_user_id
1 1 2
2 1 3
3 3 4
4 3 5
class User extends Model
{
public function connections()
{
return $this->hasMany('App\UserConnections')->with(['parent','child']);
}
}
class UserConnection extends Model
{
public function parent()
{
$this->belongsTo('App\User','parent_user_id');
}
public function child()
{
$this->belongsTo('App\User','child_user_id');
}
}
$user = App\User::find(3);
现在,当我为用户ID 3呼叫$user->connections
时,
应该给我2,3& UserConnections
表
释:
在第二行中,user3的父级是user1
在第三排&第四,user3有两个孩子
答案 0 :(得分:0)
这就解决了我的问题:
用户强>:
id username password
1 user1 ********
2 user2 ********
3 user3 ********
4 user4 ********
5 user5 ********
6 user6 ********
<强> UserConnections 强>:
pivot_id parent_user_id child_user_id relation
1 1 2 child
2 2 1 parent
3 1 3 child
4 3 1 parent
5 3 4 child
6 4 3 parent
7 3 5 child
8 5 3 parent
class User extends Model
{
public function connections()
{
return $this->belongsToMany('App\Newsroom','UserConnections','parent_user_id','child_user_id')->with(['user']);
}
}
class UserConnection extends Model
{
public function user()
{
$this->belongsTo('App\User','child_user_id');
}
}
感谢@Autista_z