【发布时间】:2020-05-21 03:41:51
【问题描述】:
我有三张桌子
类别
id | category_name | created_at | updated_at
个人资料
id | category_id | profile_name | created_at | updated_at
照片
id | profile_id | photo_name | photo_path | photo_type | created_at | updated_at
现在我需要按类别列出照片,并且每个个人资料中只需要按 photo_type 列出一张照片
我尝试过使用 hasManyhrough,但按 created_at 递减不工作
public function categoryPhotos()
{
return $this->hasManyThrough(ProfilePhoto::class,Profile::class);
}
$response=Category::with(['categoryPhotos'=>function($query){
$query->where('profile_photos.photo_type',2);
$query->orderBy('profile_photos.created_at','ASC');
$query->groupBy('profile_photos.profile_id');
}])->whereHas('categoryPhotos')->get();
如果不能通过 laravel 关系,那么 mysql 查询对我来说也很好。谢谢
【问题讨论】:
-
而且每个个人资料中只有一张照片(按 photo_type) 一组随机照片或一些确定的照片(例如,后者按创建日期)?
-
by created_at desc and phototype=2
-
我尝试过使用 hasManyhrough 但按 created_at 降序不起作用 升序 - 有效吗?
-
@Akina.asc 是默认行为,因此不会影响
-
我建议使用纯 SQL 来解决这个任务,然后看看它是否可以转换为 Laravel 语法,或者它必须作为原始执行。如果您接受这种方式,请在此级别添加表 DDL 和任务描述。 PS。 现在我需要按类别列出照片,并且每个个人资料中只需要按 photo_type 列出一张照片 - 看起来像“我需要类别列表,每个类别一张照片,前者有
created_at和 @ 987654326@"。此外 - 如果在某些类别中没有带有phototype=2(或根本没有)的照片怎么办?
标签: php mysql sql laravel laravel-5