php - 左连接在 Laravel 中获得一行

标签 php sql laravel-4 eloquent query-builder

我一直在尝试左连接并获取所需数据,但没有成功

这是我的代码:

$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();

评论是我的一些尝试...

我想只从照片表中获取一条记录匹配外键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();

@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'

用了 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`

用了 640μs - 750μs 但两者做的一样...

关于php - 左连接在 Laravel 中获得一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27317227/

相关文章:

带有二进制协议(protocol)的 PHP Memcached—— `increment()` 之后返回的垃圾数据

PHP MySQL 查询 : match two tables with percentage match

MySQL - 我的连接出了问题

php - 如何在 Laravel 4 中选择相关模型计数为 0 的模型?

php - Laravel 多对多关系获取数据

php - 使用 PDO API 防止 SQL 注入(inject)?

php - 动态 Doctrine 关系反面方法

php - 如何从 laravel 5.1 数据库表的 created_at 属性中选择年份和月份?

mysql - 如何查询 SQL 数据库以查找记录首次出现的日期?

php - 如何保存/重定向 Laravel Artisan 命令的输出?