使用Laravel 5.4,使用此
模型关系:
Painter (has many) Paintings
Hall (has many) Paintings
和逆:
Painting (belongs to one) Painter
Painting (belongs to one) Hall
霍尔控制器index()抓取集合:
$halls = Hall::with(paintings.painter)->get();
霍尔模型有一个画家访问者:
public function getPaintersAttribute() {
return \App\Painter::select('painters.*')
->join('paintings', 'painter_id', 'painters.id')
->where('paintings.hall_id', $this->id)
->groupBy('painter.id')
->orderBy('name')
->get();
}
在模板中:
{{ $hall->painters->count() }}
@foreach ($hall->painters as $painter)
painter: {{ $painter->name }}
@endforeach
这有效,但
嵌套的预先加载关系有两个数据库查询:
SELECT * FROM 'paintings' WHERE hall_id IN ( <list of hall_id's> )
SELECT * FROM 'painters' WHERE painter_id IN ( <list of painter_id's for that hall> )
还有2 * n个重复的画家查询,每个大厅两个,由访问者制作。一个用于count()另一个用于循环:
SELECT ... WHERE paintings.hall_id = <hall_id_1>
SELECT ... WHERE paintings.hall_id = <hall_id_1>
SELECT ... WHERE paintings.hall_id = <hall_id_2>
SELECT ... WHERE paintings.hall_id = <hall_id_2>
...
问题:
热切加载已经执行了对画家数据的查询,使用访问器似乎是多余的。 但我不知道如何访问它,比如
$hall->paintings->painters->count()
hasManyThrough不起作用,因为这种关系不起作用 Hall(has)Painting(has)Paintor
我可以使用数据将变量传递给控制器的视图,但由于已经加载了嵌套关系,因此看起来很奇怪。
有没有其他方法可以在视图中作为集合访问嵌套数据?