【问题标题】:Best way to get parents and children relationships within one table in laravel?在 laravel 的一张表中获得父母和孩子关系的最佳方法?
【发布时间】:2016-09-14 13:19:17
【问题描述】:

这些是我的桌子:

用户

id      username        password
1       user1           ********
2       user2           ********
3       user3           ********
4       user4           ********
5       user5           ********
6       user6           ********

用户连接

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 时;

它应该给我UserConnections 表中的 2,3 和 4 行

说明
在第二行,user3 的父级是 user1
在第三和第四行,user3 有两个孩子

【问题讨论】:

  • 我认为,如果您更改 UserConnections 表并添加 Connection 表,它会更容易、更正确。连接表——id,类型(例如:{[1 => 'parent', 2 => 'child']})并且在UserConnection中有who,with who,什么类型的连接。
  • @Autista_z 从您的解决方案中,我将不得不为单个连接创建两行,一行用于父级,另一行用于子级,我不希望这样。
  • 经过思考,我发现您的解决方案是最好的@Autista_z 感谢您的帮助。

标签: php laravel eloquent laravel-query-builder


【解决方案1】:

这就是解决我的问题的方法:

用户

id      username        password
1       user1           ********
2       user2           ********
3       user3           ********
4       user4           ********
5       user5           ********
6       user6           ********

用户连接

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

【讨论】:

  • 我很高兴能帮上忙。这肯定是更好的解决方案。现在你可以很容易地找到一个只有父母,孩子......在你原来的解决方案中,这有点难。
  • @Autista_z 没错。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 2016-05-13
  • 2022-01-13
相关资源
最近更新 更多