【问题标题】:How to query an inverse ManyToMany relationship in Laravel如何在 Laravel 中查询反向多对多关系
【发布时间】:2017-04-21 14:43:30
【问题描述】:

免责声明:我是 Laravel 新手,但对 Django 等其他 MVC 框架有经验

我有 3 张主桌和两张多对多桌。

用户可以是客户和部门的一部分,对于用户所属的每个客户,他们都有一个等级。一个客户也可以有多个部门,但一个部门只能是一个客户的一部分。

多对多(数据透视?)表大致如下所示:

client_users

- user_id
- client_id
- rank_id

department_users

- department_id
- user_id

所以在 Laravel 我有我的客户端模型:

class Client extends Model
{
    /**
    * Columns:
    * @property name = varchar(255)
    **/

    protected $table = 'clients';

    // Relationships
    public function departments() {
        return $this->hasMany('App\Models\Grouping\Department');
    }

    public function users() {
        return $this->hasMany('App\Models\Grouping\ClientUser');
    }
}

class ClientUser extends Model
{
    protected $table = 'client_users';
}

问题在于,当我执行$client->users()->get() 时,它会返回多对多数据,而不是实际用户。我希望它返回用户列表,而不是链接用户的数据列表。

我查看了文档,但无法弄清楚如何执行此操作。我必须以某种方式通过多对多,返回用户而不是多对多关系。

【问题讨论】:

    标签: php laravel-5 orm


    【解决方案1】:

    您不必将枢轴定义为单独的模型。你可以,但你不必这样做。

    只要你使用命名约定,Laravel 就会整理出要使用的枢轴。

    你正在寻找的是这样的东西(我不知道你的命名空间):

    class Client extends Model
    {
        public function departments()
        {
            return $this->hasMany(\App\Models\Grouping\Department::class); // 1:n
        }
    
        public function users()
        {
            return $this->belongsToMany(\App\Models\Grouping\User::class, 'client_users'); // will look for pivot client_users
        }
    }
    
    
    class Department extends Model
    {
        public function client()
        {
            return $this->belongsTo(\App\Models\Grouping\Client::class); // inverse 1:n
        }
    
        public function users()
        {
            return $this->belongsToMany(\App\Models\Grouping\User::class, 'department_users'); // will look for pivot department_users
        }
    }
    
    
    class User extends Authenticatable
    {
        public function clients()
        {
            return $this->belongsToMany(\App\Models\Grouping\Client::class, 'client_users'); // will look for pivot client_users
        }
    
    
        public function departments()
        {
            return $this->belongsToMany(\App\Models\Grouping\Department::class, 'department_users'); // will look for pivot department_users
        }
    }
    

    现在使用

    $client->users;
    

    将返回用户对象的集合。

    如果您需要来自数据透视表的信息(例如:rank_id),您可以这样做:

        public function users()
        {
            return $this->belongsToMany(\App\Models\Grouping\User::class)
                ->withPivot('rank_id');
        }
    

    编辑:

    ->belongsToMany() 中添加了第二个参数来定义数据透视表

    【讨论】:

    • 啊,我完全忘记了客户对用户也只是多对多。无论如何,它仍然不起作用,因为 Laravel 寻找的是 client_user 而不是 client_users。无论如何要改变它?
    • 是的,见编辑。您可以为此使用第二个参数。您可以选择使用第 3 和第 4 来定义键,但我认为您不需要它们。
    猜你喜欢
    • 2019-05-18
    • 2013-03-05
    • 1970-01-01
    • 2018-11-02
    • 2015-05-29
    • 1970-01-01
    • 2019-03-28
    • 2019-02-07
    • 1970-01-01
    相关资源
    最近更新 更多