在laravel中的非对象上调用成员函数whereHas() [英] Call to a member function whereHas() on a non-object in laravel

查看:59
本文介绍了在laravel中的非对象上调用成员函数whereHas()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我编写了以下代码

In my controller I have wrote this following code

$usersCount       = User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->count();
                $locations_array_result = explode(",",$locations_array_result);
                foreach ($locations_array_result as $param)
                {
                    $usersCount = $usersCount->whereHas('location', function($q) use($param){
                        $q->where('location_id', '=', $param );
                    });
                }

此代码给出以下错误 在非对象上调用成员函数whereHas() 谁能帮助我找出我做错了什么!!!

This code giving following error Call to a member function whereHas() on a non-object Can anyone help me to find out what i have done wrong!!!

推荐答案

在这里进行一个非常疯狂的猜测,我认为您需要让所有具有这些要求的用户

Taking a very wild guess here, I would think you need to get all users with these requirements

 ->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)

具有在名为$ locations_array_result的数组上存在的location_id值

plus having a location_id value which exists on an array named $locations_array_result

如果是这种情况,这就是您所需要的:

If this is the case, this is all you need:

User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->whereIn('location_id', $locations_array_result)->get();

编辑 根据您在下面的评论,我假设用户与位置(在模型中定义)有很多关系,因此

EDIT Following your comment below, I assume user has many to many relation with locations (defined in your model), so eager loading and then using a condition with a callback should do the job:

 $users = User::where('activated', '=', 1)
  ->where('group_id', '=', 1)
  ->where('availability_date', '<=', $opportunity_date)
  ->with(array('location' => function($query) use ($locations_array_result)
  {
    $query->whereIn('location_id', $locations_array_result); 
   }))->get();

这篇关于在laravel中的非对象上调用成员函数whereHas()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆