【问题标题】:Laravel 4.2 Eloquent fetch specific user and specific roleLaravel 4.2 Eloquent 获取特定用户和特定角色
【发布时间】:2014-08-06 17:59:26
【问题描述】:

在 Laravel Eloquent 多对多示例中,正在使用用户和角色的场景 http://laravel.com/docs/eloquent#many-to-many 说我有一组用户具有相同的家庭“辛普森”名称,我想让他们所有人都扮演角色成为“工程师”。如何使用 Eloquent 完成此任务?在示例中,使用了“has”方法http://laravel.com/docs/eloquent#querying-relations,但我如何去查询数据库以获取同时存在于用户表和角色表中的值?

我不是在寻找

User::find(1)->roles();

我正在寻找一种方法来做类似的事情

User::whereFamilyName('simpson')->roles()->whereName('Engineer')

第二个 whereName 将查询角色表而不是用户表。

【问题讨论】:

    标签: laravel-4 eloquent


    【解决方案1】:

    如果您需要获取具有特定角色的用户:

    $role = 'Engineer';
    
    // users with family name Simpson having role Engineer
    $users = User::whereFamilyName('Simpson')
          ->whereHas('roles', function ($q) use ($role) {
               $q->where('roles.name', $role); // it joins the table so you may need to use prefixed column name, otherwise you can still use dynamic whereName()
          })
          // with('roles') if needed
          ->get();
    // returns Collection of User models without roles or with all roles attached to each user if needed
    

    否则只需加入表格:

    User::whereFamilyName('Simpson')
       ->join('role_user', 'role_user.user_id', '=', 'users.id')
       ->join('roles', 'role_user.role_id', '=', 'roles.id')
       ->whereName('Engineer') // again columns name conflict may occur
       ->get(['users.*']);
    

    为了清楚起见,此处对所有值进行了硬编码。

    【讨论】:

    • 谢谢 deczo,如何在第一个示例中将参数传递给闭包函数?工程师可以改为“调酒师”。
    • +1 用于使用whereHas。很多人想要它,但使用 with 滥用它。
    【解决方案2】:

    你可以试试这个:

    $users = User::with(array('roles' => function($query){
        $query->whereName('Engineer');
    }))->whereFamilyName('simpson')->get(); // whereFamilyName = family_name in DB
    

    希望您已正确声明关系,并确保在 User 模型中与 roles 表的关系是 roles 还是 role。我使用了roles,因为您在问题代码中使用了它。

    【讨论】:

    • 这只会过滤角色对象,而不是主要结果。你应该改用whereHas
    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2021-05-05
    • 2014-08-31
    • 2021-12-11
    • 2022-01-08
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多