Laravel 4关系排序一对多计数急切加载

时间:2014-05-04 19:14:13

标签: php laravel count one-to-many eloquent

不确定这是否可行。我可以对当前表格中的所有内容(标题,正文等)进行排序,但还没有想到将其排序到与之相关的表格中。我想根据他/她拥有DESC,ASC的歌曲总数来对艺术家进行排序。

如何动态排序艺术家的歌曲总数?

管理员/艺术家sortby =歌曲&安培;为了= ASC

Screenshot

我的桌子

艺术家:id,name,body,slug

歌曲:id,title,body,slug,hits,artist_id

在此之前我在控制器中使用了eager loading,Artist :: with('songs)... 然后在我可以在foreach循环中使用的视图中,对总歌曲进行计数($ artist->歌曲)。然后我找到了一种更清洁的方式 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 个答案:

答案 0 :(得分:0)

你必须加入这些表格。

Artist::join('songs', ...)
  ->orderByRaw('count(songs.*) asc')
  ->select('artists.*')
  ->get();