Ron*_*ser 6 php sql query-builder eloquent laravel-4
我没有成功尝试leftjoin并获得所需的数据
这是我的代码:
$album = Albums::->where('users_id',$user_id)
->leftJoin('photos',function($query){
$query->on('photos.albums_id','=','albums.id');
$query->where('photos.status','=',1);
// $query->limit(1);
// $query->min('photos.created_at');
})
->where('albums.status',1)->get();
Run Code Online (Sandbox Code Playgroud)
评论是我的几个尝试......
我想从照片表中只获得一张与album_id首先更新的外键相关的记录,并且状态为1
请帮忙......
我用DB::raw()它来实现这一目标
$album = Albums::select( 'albums.*',
DB::raw('(select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo') )
->where('users_id',$user_id)
->where('albums.status',1)->get();
Run Code Online (Sandbox Code Playgroud)
@JarekTkaczyk的编码类似,并显示了我所需的相同结果,所以特别感谢他的时间和精力......
但是将quires我留下的执行时间与我的上述片段进行比较
select `albums`.*, (select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo from `albums` where `users_id` = '1' and `albums`.`status` = '1'
Run Code Online (Sandbox Code Playgroud)
拿 520?s - 580?s
和@JarekTkaczyk的
select `albums`.*, `p`.`photo` from `albums` left join `photos` as `p` on `p`.`albums_id` = `albums`.`id` and `p`.`created_at` = (select min(created_at) from photos where albums_id = p.albums_id) and `p`.`status` = '1' where `users_id` = '1' and `albums`.`status` = '1' group by `albums`.`id`
Run Code Online (Sandbox Code Playgroud)
拿了 640?s - 750?s但两者也一样...
您可以使用它实现任意leftJoin或rightJoin(但后者将返回Photo的车型,所以可能你不会需要一个):
Albums::where('users_id', $user_id)
->leftJoin('photos as p', function ($q) {
$q->on('photos.albums_id', '=', 'albums.id')
->on('photos.updated_at', '=',
DB::raw('(select min(updated_at) from photos where albums_id = p.albums_id)'))
->where('photos.status', '=', 1);
})
->where('albums.status', 1)
->groupBy('albums.id')
->select('albums.*', fields from photos table that you need )
->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14738 次 |
| 最近记录: |