我正在使用larvel eloquent。 我正在使用模型使用此查询。我的代码是
$books = Book::select('title', 'author', Book::raw('count(*) as copies'))
->where('title', 'like', '%'.$name.'%')
->orWhere(function ($query) use ($name) {
$query->where('author', 'like', '%'.$name.'%')
->where('subject', 'like', '%'.$name.'%');
})
->groupBy('title','author')
->get();
我收到错误 “strtolower() 期望参数 1 为字符串,给定对象” 我知道错误出现在 count() 中。代码 raw('count() as Copys') 用于table。 但我不知道如何在模型 Eloquent 中使用 count(*) 作为副本。我的型号名称是Book。 我还有一个疑问,我们可以在 groupBy 中使用多个字段吗? groupBy('标题','作者')
最佳答案
使用selectRaw()
$books = Book::select('title', 'author'))
->where('title', 'like', '%'.$name.'%')
->orWhere(function ($query) use ($name) {
$query->where('author', 'like', '%'.$name.'%')
->where('subject', 'like', '%'.$name.'%');
})
->selectRaw('count(*) as copies')
->groupBy('title','author')
->get();
关于php - 如何在 Laravel 中将 count(*) 设置为字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48902299/