使用whereRaw()和orWhereRaw()与laravel 5.2中的Join

时间:2017-12-06 10:48:27

标签: php laravel laravel-5.2 laravel-eloquent

我正在写这样的代码: -

$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details', function($query) use ($rating,$keyword) {
            $query->on('users.id', '=', 'homechef_details.user_id');
            $query->where('users.status','=',1);
            if(isset($rating) && !empty($rating)) 
            {
                if(count($rating)==1)
                    $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                    $query->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
        })->get();

我需要检查where子句中列值的floor值。我收到了这个错误: -

Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()

如何解决此错误?

2 个答案:

答案 0 :(得分:2)

看来JoinClause类没有原始查询的方法,我建议你试试像

这样的东西
$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details','users.id', '=', 'homechef_details.user_id')->where('users.status','=',1);
            if(isset($rating) && !empty($rating)) 
            {
                if(count($rating)==1)
                   $results = $results->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                   $results = $results->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
 $results = $results->get();

答案 1 :(得分:1)

内部关闭,$queryJoinClause的实例,并且没有whereRaw()方法。

作为madalinivascu的答案的替代方法,您可以使用DB::raw()在封闭内构造原始SQL。