【问题标题】:Having trouble doing a "where" in a many to many relationship在多对多关系中做“哪里”有困难
【发布时间】:2014-02-09 12:59:38
【问题描述】:

例如,我有UsersRoles 和一个名为user_role 的多对多表。我想做类似User::with('roles')->where('role', '=', 'admin')->get() 的事情。但是它无法识别Roles 表中的“角色”字段。我怎样才能在不是中间表而是在另一个加入的表上实现where 子句?

我的多对多关系是如何定义的:

class User extends Eloquent {

    public function roles()
    {
        return $this->belongsToMany('Role');
    }

}

【问题讨论】:

    标签: sql laravel many-to-many eloquent


    【解决方案1】:

    感谢laravel.io 的耐心人士:

    User::whereHas('roles', function($query)
    {
      $query->where('role', '=', 'admin');
    })->get();
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 2014-06-12
      • 2014-06-12
      • 2020-06-18
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      相关资源
      最近更新 更多