不确定这是否可行 . 我可以对当前表格中的所有内容( Headers ,正文等)进行排序,但还没有想到将其排序到与之相关的表格中 . 我想根据他/她拥有DESC,ASC的歌曲总数来对艺术家进行排序 .
How can I dynamically sort the total number of songs from the artists?
管理员/艺术家?sortby =首歌曲和秩序= ASC
我的 table
艺术家:id,name,body,slug
歌曲:id,title,body,slug,hits,artist_id
在此之前我使用了控制器中的热切加载,Artist :: with('songs)...然后在视图中我可以在foreach循环中使用,计算($ artist-> songs)的总歌曲 . 然后我发现了一种更清洁的方式http://laravel.io/forum/05-03-2014-eloquent-get-count-relation
艺术家模型
public function songs()
{
return $this->hasMany('Song');
}
public function songsCountRelation()
{
return $this->hasOne('Song')->selectRaw('artist_id, count("id") as count')->groupBy('artist_id');
}
public function getSongsCountAttribute()
{
return $this->songsCountRelation->count;
}
歌曲模型
public function artist()
{
return $this->belongsTo('Artist');
}
调节器
public function index()
{
// Sortby and order variables from url
$this->data['sortby'] = Input::get('sortby');
$this->data['order'] = Input::get('order');
// If the sortby and order exists in url, fetch the data and order it accordingly
if ($this->data['sortby'] && $this->data['order'])
{
// Order the data based on keys from url
$this->data['artists'] = Artist::with('songsCountRelation')->orderBy($this->data['sortby'], $this->data['order'])->get(['id', 'name', 'body', 'slug']);
}
else
{
$this->data['artists'] = Artist::with('songsCountRelation')->get(['id', 'name', 'body', 'slug']);
}
$this->layout->content = View::make('admin.artists.index', $this->data);
}
索引视图
<th>
{{--Sort by slug--}}
@if ($sortby == 'slug' && $order == 'asc')
{{ link_to_route('admin.artists.index', 'Slug', ['sortby' => 'slug', 'order' => 'desc']) }}
@else
{{ link_to_route('admin.artists.index', 'Slug', ['sortby' => 'slug', 'order' => 'asc']) }}
@endif
</th>
<th>
{{--Sort by total songs--}}
@if ($sortby == 'songs' && $order == 'asc')
{{ link_to_route('admin.artists.index', 'Songs', ['sortby' => 'songs', 'order' => 'desc']) }}
@else
{{ link_to_route('admin.artists.index', 'Songs', ['sortby' => 'songs', 'order' => 'asc']) }}
@endif
</th>
...¨
@foreach($artists as $artist)
<tr>
...
<td>{{ $artist->songsCount; }}</td>
...
</tr>
@endforeach
提前致谢!
1 回答
你必须加入这些表格 .