【问题标题】:how to retrieve eloquent model, where a field in a related model equals "xx"?如何检索 eloquent 模型,其中相关模型中的字段等于“xx”?
【发布时间】:2017-10-11 18:22:48
【问题描述】:

我有两个模型“user”和“user_groups”

两个模型之间存在如下关系:

public function usergroup()
{
    return $this->hasOne('App\user_group','id','group_id');
}

我可以使用这种方法获取“drivers”组的所有用户。

 $driversx = User::where('group_id',3)->get();

但我想使用“user_groups”模型中的“group_name”字段来获取这些用户。

我怎样才能做到这一点?

【问题讨论】:

  • 在您的 user_groups 模型中添加属于关系
  • 你能举个清楚的例子吗?谢谢...

标签: php mysql laravel model eloquent


【解决方案1】:

对于你的 belongsTo 关系:

public function users()
{
    return $this->hasMany('App\User','id','group_id');
}

然后:

$users = UserGroup::where('group_name', 'drivers')->first()->users

您的模型名称可能不是 UserGroup :)

【讨论】:

    【解决方案2】:

    使用whereHas()方法:

    User::whereHas('usergroup', function ($q) {
        $q->where('group_name', 'drivers');
    })->get();
    

    【讨论】:

      【解决方案3】:

      一般我们都是这样使用的

        public function Menus(){
      
           return $this->hasOne('App\Models\MainMenu', 'id', 'menu_id');
      }
      

      控制器:

      $menu_listing=MenuListing::with('Menus')->get();
      

      但是如果你想使用 group_name 去belongs to

      【讨论】:

      • 我想用 group_name ,你能举个清楚的例子吗?
      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多