【问题标题】:how to set count(*) as field name in laravel如何在laravel中将count(*)设置为字段名
【发布时间】:2018-02-21 09:28:30
【问题描述】:

我正在使用 larvel 雄辩。 我正在使用模型使用此查询。我的代码是

$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 copies') 用于table。 但我不知道如何在模型 eloquent 中使用 count(*) 作为副本。我的模特名称是Book。 我还有一个疑问,我们可以在 groupBy 中使用多个字段,即 groupBy('title','author')

【问题讨论】:

标签: php mysql laravel eloquent


【解决方案1】:

使用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();

【讨论】:

    【解决方案2】:

    试试这个,SelectRaw

    $books = Book::select('title', 'author')
        ->selectRaw('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();
    

    你也有这种可能性

    ->select('title','author', DB::raw('count(*) as copies'))
    

    Laravel Documentation Raw

    【讨论】:

    • 他没有任何pricedepartment
    • 抱歉...复制粘贴
    • 是的,它有效。节省大量时间。 selectRaw('count(*) as copies')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2018-01-04
    • 2013-02-16
    • 2020-09-20
    • 2021-06-20
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多