사진을 나타내는 앨범 모델과 AlbumItem 모델이 있습니다. 앨범 모델에서Eloquent hasOne by group by
내가 가진 : 컨트롤러에서
public function first_photo(){
return $this->hasOne('AlbumItem')->orderBy('sort_order', 'asc');
}
은 내가 먼저 사진으로 앨범을 목록을로드는 :
select * from `album_items`
where `album_items`.`album_id` in (1,2,3,4,5) order by `sort_order` asc
:
Album::with(['first_photo'])->get();
그것은이 같은 SQL 쿼리를 생성
하지만 album_id = 1,2,3 인 모든 앨범 항목을 반환합니다. 4,5 ...
그리고 가장 작은 값이 sort_order
인 첫 번째 앨범 항목 만 필요하므로 GROUP BY를 사용하려고했지만 ORDER BY가 작동하지 않습니다 ... 즉 first_photo()
메서드를 변경하려고합니다. sort_order
BY 첫 번째 순서, 다음 album_id
BY GROUP :
select * from (
select * from `album_items`
where `album_items`.`album_id` in (1,2,3,4,5) order by `sort_order` asc
) temp
group by temp.`album_id`
그것은 hasOne
방법이 얻을 수 있습니까?
..'$ this-을 반환> hasOne의 ('AlbumItem') -> 해 orderBy ('SORT_ORDER', '오름차순'는);'-,하지 마십시오 [범위] (https를 사용 : //laravel.com/docs/5.3/eloquent#query-scopes) 대신 *.하지만 album_id = 1,2,3,4,5 * 인 모든 앨범 항목을 반환합니다. 예, 그렇습니다. (그리고 'AlbumItem'은 관련된'앨범들 '에 매핑 될 것입니다.) ..에 관한, 그리고 가장 작은 값을 가진 첫 번째 앨범 항목 만 필요합니다. - 열정적 인 로딩 제약 조건 (https : // laravel.com/docs/5.3/eloquent-relationships#constraining-eager-loads). –