php - SQL Select Join with a limit in Laravel/PHP

标签 php mysql laravel

我最初的查询是搜索主板,然后找到主板的图像。但是现在,一些主板没有任何关联的图像,所以我想运行一个查询来找到 20 个带有图像的独特主板。

到目前为止的代码:

$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
    ->where('images.item_type', '=', 'motherboard')
    ->orderBy('motherboards.date_added', 'desc')
    ->take(20)
    ->get();

我什至尝试过选择特定结果:

$newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
    ->select('motherboards.motherboard_id', 'motherboards.name')
    ->where('images.item_type', '=', 'motherboard')
    ->orderBy('motherboards.date_added', 'desc')
    ->take(20)
    ->get();

上面代码的问题在于,当我循环遍历每个 $newMotherboards 时,它会为每个具有其 ID 的图像提供重复项。我只想检索最近添加的 20 个独特的主板,但有图像。

如果一个项目有 5 张图片,并且是最近添加的 20 张图片之一,那么它将出现 20 张限制的五次。

最佳答案

不同版本:

    $newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
        ->select('motherboards.motherboard_id', 'motherboards.name')
        ->where('images.item_type', '=', 'motherboard')
        ->distinct()
        ->orderBy('motherboards.date_added', 'desc')
        ->take(20)
        ->get();

分组版本:

    $newMotherboards = Motherboards::join('images', 'motherboards.motherboard_id', '=', 'images.item_id')
        ->select('motherboards.motherboard_id', 'motherboards.name')
        ->where('images.item_type', '=', 'motherboard')
        ->groupby('images.item_type')
        ->orderBy('motherboards.date_added', 'desc')
        ->take(20)
        ->get();

关于php - SQL Select Join with a limit in Laravel/PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28849719/

相关文章:

php,异常可以向上抛出2级吗?

php - 整理MYSQL数据

php - SQL 查询 - WHERE 语句的问题

php Laravel ~ 属性 [controller] 不存在

php - 从服务器 > 服务器 > 客户端传输,无需下载到服务器

php - MySQL和Codeigniter项目中数据的加解密

php - mysql 获取值(值结束=0)

mysql - 如何通过对子表中的值进行 JOINing 和 SUM 来更新表 1 中的缓存值?

php - 从今天开始循环以从一组模板生成类次/轮类列表

postgresql - 如何在cmd中登录postgreSQL