You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel查询构造器或Eloquent实现指定SQL语句?

用Laravel查询构造器和Eloquent实现指定SQL

嘿,我帮你把这条SQL转换成Laravel的两种实现方式,完全对应你原SQL的逻辑:先随机取10个目标分组下的活跃分类,再从这些分类里随机挑3个活跃商品。

一、查询构造器写法

直接对应原SQL的嵌套子查询结构,一步步实现:

$groupCategoryId = 12;

$products = DB::table('product')
    ->whereIn('CategoryID', function ($query) use ($groupCategoryId) {
        // 内层子查询:先取10个随机的目标分组下的活跃分类
        $query->select('CategoryID')
            ->from(function ($subQuery) use ($groupCategoryId) {
                $subQuery->select('CategoryID')
                    ->from('category')
                    ->where('GroupCategoryID', $groupCategoryId)
                    ->where('IsActive', 1)
                    ->orderByRaw('RAND()')
                    ->limit(10);
            }, 't');
    })
    ->where('IsActive', 1)
    ->orderByRaw('RAND()')
    ->limit(3)
    ->get();

二、Eloquent写法(假设已定义模型关联)

先确保你的模型和关联关系已经正确定义:

  • Product 模型:属于 Category(product.CategoryID 关联 category.CategoryID)
  • Category 模型:属于 GroupCategory(category.GroupCategoryID 关联 group_category.GroupCategoryID)

然后可以用更直观的分步查询实现:

// 先获取目标分组下随机10个活跃分类的ID集合
$categoryIds = Category::where('GroupCategoryID', 12)
    ->where('IsActive', 1)
    ->orderByRaw('RAND()')
    ->limit(10)
    ->pluck('CategoryID');

// 再从这些分类中随机取3个活跃商品
$products = Product::whereIn('CategoryID', $categoryIds)
    ->where('IsActive', 1)
    ->orderByRaw('RAND()')
    ->limit(3)
    ->get();

如果想写成链式嵌套子查询的形式,也可以这样:

$groupCategoryId = 12;

$products = Product::whereIn('CategoryID', function ($query) use ($groupCategoryId) {
    $query->select('CategoryID')
        ->from(function ($subQuery) use ($groupCategoryId) {
            $subQuery->select('CategoryID')
                ->from('categories') // 注意:如果Category模型默认表名是复数(Laravel默认规则),这里要对应修改
                ->where('GroupCategoryID', $groupCategoryId)
                ->where('IsActive', 1)
                ->orderByRaw('RAND()')
                ->limit(10);
        }, 't');
})
->where('IsActive', 1)
->orderByRaw('RAND()')
->limit(3)
->get();

小提示:如果你的数据库是PostgreSQL,需要把 orderByRaw('RAND()') 改成 orderByRaw('RANDOM()'),不同数据库的随机排序函数有差异哦。

内容的提问来源于stack exchange,提问作者calin24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:55