Support the ongoing development of Laravel.io →
posted 7 years ago
Eloquent
$data = StoneType::with(['user'=>function($query){
        // 每个取 2 条
        return $query->where(\DB::raw('2'),'>',function($query){
            return $query->select(\DB::raw('count(id)'))->from('users as u')
                ->where('u.stone_id','=','users.stone_id')->where('u.id','>','users.id');
        });
}])->limit(4)->orderBy('sort', 'asc')->get();

\DB::getQueryLog result:

select * from `users` where `users`.`stone_id` in (?, ?, ?, ?) and 2 > (select count(id) from `users` as `u` where `u`.`stone_id` = ? and `u`.`id` > ?)

SQL Result:

eloquent result will get all data like sql select * from users where stone_id in ...

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

cevin cevin Joined 22 Apr 2018

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.