Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1对多关系的表,获取1表的20条数据,同时获取多表最新几条数据 #16

Open
clms2 opened this issue Aug 24, 2018 · 0 comments

Comments

@clms2
Copy link
Owner

clms2 commented Aug 24, 2018

获取用户的订单时只获取最新的2条:

$dbprefix = config('database.connections.mysql.prefix');
$orderCount = 2;
$users = User::with(['order' => function($q) use($dbprefix, $orderCount){    
    $q->select(['o.order_id','o.user_id','o.order_sn'])
    ->leftJoin('order as o', function($join){
        $join->on('o.user_id', '=', 'order.user_id')->on('order.order_id', '>=', 'o.order_id');
    })
    ->groupBy('o.user_id')
    ->groupBy('o.order_id')
    ->having(DB::raw("count({$dbprefix}o.order_id)"), '<=', $orderCount);
}])->limit(20)->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant