在 Laravel 5.2 中使用 whereRaw() 和 orWhereRaw() 与 Join
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47672441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using whereRaw() and orWhereRaw() with Join in laravel 5.2
提问by Saswat
I am writing a code like this:-
我正在编写这样的代码:-
$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();
I need to check the floor value of the column value in the where clause. I am getting this error:-
我需要检查 where 子句中列值的下限值。我收到此错误:-
Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()
How can I fix this error?
我该如何解决这个错误?
回答by madalinivascu
It seems that the JoinClause class doesn't have a method for raw queries, i suggest you try soemthing like
似乎 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();
回答by Zamrony P. Juhara
Inside closure, $queryis instance of JoinClauseand it does not have whereRaw()methods.
在闭包内部,$query是实例JoinClause并且它没有whereRaw()方法。
As alternative to madalinivascu's answer, you can use DB::raw()to construct raw SQL inside closure.
作为 madalinivascu 答案的替代方案,您可以使用DB::raw()在闭包内构造原始 SQL。

