2016-11-21 9 views
1

私はUserActionを持つActionモデルを持っています。私はどれくらいの数を得る必要があるUserActionsそれぞれのためにあるAction。これのSQLは次のとおりです。グループ化された関連モデルのカウントを取得するためのきわめて正確なクエリ

SELECT *, count(*) as count 
FROM user_actions JOIN actions 
    ON user_actions.action_id=actions.id 
GROUP BY actions.id; 

そして私はちょうどEloquentクエリでこれを行う方法があるのだろうか?

ありがとうございました。

答えて

0

私は、これは私がいくつかのように得ることができる最も近いですが、それを解決しました未処理クエリ(またはEloquent-y)を可能な限り使用します。

UserAction::select(DB::raw('actions.id, actions.name, COUNT(*) AS count')) 
        ->join('actions', 'actions.id', '=', 'user_actions.action_id') 
        ->groupBy('actions.id')->get(); 
1

ActionモデルにuserActionsリレーションシップを設定していることを確認してください。

例:(名前空間AppUserActionモデルを持っていると仮定すると)

class Action extends Model 
{ 
    public function userActions() 
    { 
     return $this->belongsToMany('App\UserAction'); 
    } 
} 

はその後、それがこれを行うのと同じくらい簡単です:

//$action = some action 

$count = $action->userActions->count(); 

雄弁な関係は、コレクションを返す:https://laravel.com/docs/5.3/eloquent-relationships

countは、Eloquentコレクション(Laravel collections)によって提供される方法です:https://laravel.com/docs/5.3/collections#method-count

1

Laravel 5.2以降では、1対多の関係のためにwithCountメソッドを使用できます。 official documentationから

あなたが実際にそれらをロードすることなく関係からの結果の数をカウントしたい場合は、あなたの結果のモデルに{関連} _count列を配置しますwithCountメソッドを使用することができます。あなたの状況では

$posts = App\Post::withCount('comments')->get(); 

foreach ($posts as $post) { 
    echo $post->comments_count; 
} 

セットアップ関係を持っている場合、このようなものが動作するはずです:例えば

$user_actions = App\UserActions::withCount('actions')->get(); 

foreach ($user_actions as $action) { 
    echo $action->actions_count; 
} 
関連する問題