【问题标题】:I want to pass this query to Eloquent in laravel我想将此查询传递给 laravel 中的 Eloquent
【发布时间】:2018-09-13 13:20:20
【问题描述】:

我正在尝试使用 eloquent 进行查询,我尝试获取所有拥有一个或多个广告的用户,同时考虑到这是一对多的关系(用户与广告)。

这个查询通常做我想要的,但我不知道它是否做得很好,也不知道如何通过用户模型将它传递给 Eloquent。

 SELECT users.id, COUNT( anuncio.id ) AS  'total' FROM users 
INNER JOIN anuncio ON users.id = anuncio.usuario_id WHERE 
(SELECT COUNT( * ) FROM anuncio WHERE anuncio.usuario_id = users.id) >0 
GROUP BY users.id ORDER BY total DESC

我尝试了几种只将 Builder 返回给我的方法。 例如:

$listas = new User;
        $listas = $listas->join('anuncio','users.id','=','anuncio.usuario_id');
        $listas = $listas->select(array('users.*', DB::raw('COUNT(anuncio.id) AS total')));
        $listas = $listas->where(function($query) use ($listas){
            $query->select(DB::raw('COUNT(anuncio.usuario_id)'))
                    ->where('anuncio.usuario_id','=','users.id')
                    ->groupBy('anuncio.usuario_id');
        },'>','0');
        $listas = $listas->orderBy('total','DESC')->paginate(48);

如有任何建议,我将不胜感激。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    试试这个

    $listas = User::join('anuncio','users.id','=', 'anuncio.usuario_id')
    ->select('users.id',DB::raw("count(anuncio.id) as total"))
    ->groupby('users.id')
    ->having('total', '>', '0')
    ->orderby('total', 'desc')
    ->get();
    

    【讨论】:

    • 结果如下:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total>0' in 'have Clause' (SQL: select count(*) as aggregate from users inner加入anuncio on users.id = anuncio.usuario_id group by users.idtotal>0 = )...不识别列总数,我试图改变 - >have('total','>',0) 但同样的错误
    • having ('total>0) 替换为->having('total', '>', '0')
    • 在 config/database.php 中更改严格值。设置为假
    • 成功了,非常感谢,但现在我无法使用 paginate() 你知道为什么吗?
    • 我们可以通过将别名总数更改为聚合来使代码正常工作。但是按照标准我不知道这是否合适。
    【解决方案2】:

    只需使用左连接即可。

    $users = DB::table('users')
                ->leftJoin('anuncio', 'users.id', '=', 'anuncio.usuario_id')
                ->get();
    

    所以Left Join 只会选择那些在anuncio 表中匹配的结果。

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 2021-12-29
      • 1970-01-01
      • 2012-12-25
      • 2019-02-21
      • 2020-06-18
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多