【问题标题】:Laravel select count in select选择中的 Laravel 选择计数
【发布时间】:2015-08-27 04:32:46
【问题描述】:

我使用 laravel 4.2, 我有一个名为 pois 的表,其中包含一些 poi(poi = 兴趣点),我还有一个名为 stamps 的表,其中包含用户标记。

所以我想要用户拥有最大邮票数量的 3 个 pois。 我的问题是我不知道如何使用 laravel 查询。 我使用 sql 请求得到了结果,但这不是执行此操作的好方法。 这里是我的 sql 请求:

$pois = DB::select("SELECT *, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps FROM pois order by nbr_stamps DESC limit 3");

你能告诉我如何使用 laravel 查询来做到这一点吗?

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    您应该使用selectRaw() 而不是select() 并将查询的其他部分与相关方法分开:

    $pois = DB::select(DB:raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))
        ->from('pois')
        ->orderBy('nbr_stamps', 'DESC')
        ->limit(3);
    

    阅读Query Builder documentation

    【讨论】:

    • 快速回复,好!
    • 谢谢,但我收到以下错误:call_user_func_array() 期望参数 1 是有效的回调,类 'Illuminate\Database\MySqlConnection' 没有方法 'selectRaw'
    • @Barzull DB 应该是 Illuminate\Support\Facades\DB。将use DB 添加到文件顶部,然后重试。
    • 我尝试使用 Illuminate\Support\Facades\DB 作为控制器顶部的数据库;但没有任何改变;(
    • 将结果粘贴到这里:var_dump(get_class(new DB))
    【解决方案2】:

    感谢 limonte 提供的文档链接,我找到了选择 raw 的正确书写方式,这里是解决方案:

    $pois = DB::table('pois')
            ->select(DB::raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))
            ->orderBy('nbr_stamps', 'DESC')
            ->take(3)
            ->get();
    

    祝你有美好的一天;)

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多