laravel 5 查询生成器错误“必须是数组类型,给定对象”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31071665/
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
laravel 5 Query Builder error "must be of the type array, object given"
提问by Matthew Smart
Ok so i am trying to perform a mysql query to join to tables and return the results.
好的,所以我正在尝试执行 mysql 查询以加入表并返回结果。
So in my controller i have an array of serviceIDs that when print_r() looks like this:
所以在我的控制器中,我有一个 serviceID 数组,当 print_r() 看起来像这样:
Array
(
[0] => 50707
[1] => 50709
)
The name of this array is $serviceIDS
这个数组的名字是 $serviceIDS
Okay Then i now call a function from one of my models. This is a scope as seen below:
好的然后我现在从我的一个模型中调用一个函数。这是一个范围,如下所示:
$services = Services::getWatchListInfo($serviceIDS)->get();
This is the scope function in my model:
这是我模型中的作用域函数:
public function scopegetWatchListInfo($serviceIDS){
$services = DB::table('services')
->join('reviews','services.serviceID','=','reviews.serviceID')
->select('services.name','services.type','services.review_count_approved','reviews.escalate','reviews.average_rating')
->whereIn('serviceID',$serviceIDS);
return $services;
}
Okay so this should get results from both my services and reviews table where service id is in the array.
好的,所以这应该从我的服务和评论表中获得结果,其中服务 ID 位于数组中。
Instead i am getting the following error.
相反,我收到以下错误。
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, object given, called in /Users/user/sites/informatics-2/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 311 and defined
Any ideas?
有任何想法吗?
采纳答案by Kirk Beard
You're not using Eloquent scopes correctly. If you read the docs, you're attempting to use a Dynamic Scope, so you need to define your scope as:
您没有正确使用 Eloquent 范围。如果您阅读 docs,则您正在尝试使用动态范围,因此您需要将范围定义为:
/**
* getWatchList Eloquent Scope
*
* @param object $query
* @param array $servicesIDS
* @return object $query
*/
public function scopegetWatchListInfo($query, $serviceIDS = []) {
return $query
->join('reviews','services.serviceID','=','reviews.serviceID')
->select('services.name','services.type','services.review_count_approved','reviews.escalate','reviews.average_rating')
->whereIn('serviceID', $serviceIDS);
}
The DB::table('services')
should not be necessary if you're defining a Scope within your Services
model (because the services
table is automatically handled by Eloquent:
的DB::table('services')
,如果你的内限定范围不应该是必要的Services
模型(因为services
表自动雄辩处理:
Now, let's look at an example
Flight
model class, which we will use to retrieve and store information from ourflights
database table
现在,让我们看一个示例
Flight
模型类,我们将使用它从我们的flights
数据库表中检索和存储信息