【问题标题】:Errors using Laravel's Eloquent relationship使用 Laravel 的 Eloquent 关系的错误
【发布时间】:2017-11-06 14:32:22
【问题描述】:

我有 2 个模型 - 用户和角色用户。每个用户都被分配了一个角色。所以我通过在 User 模型上声明一个“角色”方法来定义一对一的关系。

 public function role(){
        return $this->hasOne('Vanguard\RoleUser', 'user_id');
 }

这是我的榜样

class RoleUser extends Model
{
    //
    public $table = 'role_user';

    protected $fillable = ['user_id', 'role_id'];

}

在控制器中,我试图获取 role_id = 2 的用户,但查询不断返回所有用户(即 3 个)而不是一个用户。 这是我的控制器

 $users = User::with(['role' => function ($query) {
            $query->where('role_id', 2);
        }])->get();

请问这是什么原因造成的?

【问题讨论】:

  • 什么版本的 Laravel?

标签: php laravel


【解决方案1】:

使用with 的作用域只会将作用域添加到急切加载的关系中,而不管它是否存在。要实现您想要的,您也需要发送whereHas

$users = User::whereHas('role', function ($q) {
    $q->where('role_id', 2);
})->with(['role' => function ($q) {
    $q->where('role_id', 2);
}])->get();

【讨论】:

    【解决方案2】:

    将查询更改为如下所示:

    User::all()->with('role')->where('role_id', 2)->get()

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      假设您已定义:

      • 一个用户只有一个角色。
      • 一个角色有很多用户。

      那么您可以简单地将查询编写为:

      $role = Role::with('users')->find(2);
      $users = $role->users;
      

      上面的示例将为您提供角色 id 为 2 的所有用户。

      【讨论】:

        【解决方案4】:

        假设每个用户可能只有一个角色,那么试试这个:

        在您的用户模型中:

        class User extends Model 
        {
            public function role()
            {
                return $this->belongsTo(RoleUser::class);
            }
        }
        

        在您的 RoleUser 模型中:

        class RoleUser extends Model
        {
            public function users()
            {
                return $this->hasMany(User::class);
            }
        }
        

        现在,获取您需要的数据(先在 Tinker 中尝试):

        // Users with role_id 2
        $users = User::where('role_id', 2)->get();
        
        // Eager load the Role model to get the entire Role record for each user
        $users = User::with('role')->where('role_id', 2)->get();
        
        // Get role's where role_id is 2, and eager load the users
        $role = RoleUser::with('users')->where('id', 2)->get();
        

        【讨论】:

          猜你喜欢
          • 2020-05-02
          • 2019-02-13
          • 1970-01-01
          • 1970-01-01
          • 2013-09-28
          • 2016-11-21
          • 2015-01-03
          • 2021-07-29
          • 2019-07-27
          相关资源
          最近更新 更多