sql查询到子查询的laravel查询

时间:2017-12-17 15:48:02

标签: php jquery mysql laravel

请帮助如何使这个sql正确,不能使用两个select和RAND

SELECT * FROM (SELECT * FROM `galleries` 
               WHERE domain_id = 13 AND is_deleted = 0 
               ORDER BY galleries.id DESC LIMIT 30) q 
ORDER BY RAND()

喜欢这个

$galleries = DB::table('galleries')->select( DB::raw('galleries.*') )
            ->where( 'domain_id', 13 )
            ->where( 'is_deleted', 0 ) ...

1 个答案:

答案 0 :(得分:0)

您可以将查询重写为

SELECT * FROM `galleries`
WHERE domain_id = 13 
AND is_deleted = 0 
ORDER BY id DESC,RAND()
LIMIT 30

在laravel中像

$galleries = DB::table('galleries')
            ->select( DB::raw('galleries.*') )
            ->where( 'domain_id', 13 )
            ->where( 'is_deleted', 0 )
            ->orderBy('id', 'desc')
            ->orderByRaw('RAND()')

或者在不应用->orderByRaw('RAND()')并执行shuffle()

的情况下从上述查询中获取结果
$galleries = $galleries->toArray(); 
shuffle($galleries);