クエリ内でクエリを実行する方法を理解しようとしています。(それが理にかなっているなら)私はすべての活動をつかみたいです。アクティビティごとに、アクティビティを実行したユーザーの数を取得したいと思います。次に、各アクティビティを実行したユーザーの数に基づいて、すべてのアクティビティをDESC順に並べます。私は基本的に「人気のあるアクティビティページ」を作成しており、ほとんどのユーザーが行ったアクティビティから始まるすべてのアクティビティを表示しています。
私はこれのために3つのメインテーブルを持っています
ユーザー
| id | name | password | email | created_at |
活動
| id | title | description | created_at |
リソースこれは、どのユーザーがどのアクティビティを実行したかを示す投稿に使用しているテーブルです。(ユーザーは自分が行ったアクティビティを表示し、メディアと場所を投稿に添付できます)
| id | user_id | activity_id | media_id | location_id | created_at |
これが各テーブルの私のモデルです
ユーザーモデル
class User extends Eloquent {
protected $table = 'users';
/**
* get the activities associated with the given user
* @return mixed
*/
public function activities()
{
return $this->belongsToMany('Acme\Activities\Activity', 'resource', 'activity_id');
}
public function posts(){
return $this->hasMany('Acme\Resource\Resource');
}
public function media()
{
return $this->hasMany('Acme\Media\Media');
}
public function locations()
{
return $this->hasMany('Acme\Locations\Location');
}
}
活動モデル
class Activity extends Eloquent {
protected $table = 'activities';
public function posts(){
return $this->hasMany('Acme\Resource\Resource', 'resource_id');
}
/**
* get the users associated with the given activity card
* @return mixed
*/
public function users()
{
return $this->belongsToMany('Acme\Users\User', 'resource', 'user_id');
}
}
リソースモデル
class Resource extends Eloquent {
protected $table = 'resource';
public function user()
{
return $this->belongsTo('Acme\Users\User', 'user_id');
}
public function activities()
{
return $this->belongsTo('Acme\Activities\Activity', 'activity_id');
}
public function media()
{
return $this->hasMany('Acme\Media\Media', 'media_id');
}
public function locations()
{
return $this->belongsTo('Acme\Locations\Location', 'location_id');
}
}
私は私が使用してすべての活動を得ることができることを知っています
Activity::get()
を使用して特定のアクティビティのユーザー数を取得できます
User::whereHas('resource', function($q) use ($activity_id){
$q->where('activity_id', $activity_id);
})->get()->count();
しかし、ユーザー数が最も多いアクティビティから始めて、すべてのアクティビティをユーザー数で並べ替えるために、これらすべてをどのように組み合わせることができるかわかりません。
雄弁なものを使用してこのクエリを作成するにはどうすればよいですか?
前もって感謝します!
試してみてください
Resource::select(DB::raw('*, COUNT(distinct(user_id)) as user_count'))->group_by('activity_id')->order_by('user_count', 'desc')->get();
その後、これを行うことができます
$results = Resource::select(DB::raw('*, COUNT(distinct(user_id)) as user_count'))->group_by('activity_id')->order_by('user_count', 'desc')->get();
foreach ($results as $result) {
$activity = Activity::where('id','=',$result->activity_id)->first();
// do stuff to display data for this activity like
// $activity->title or $activity->description
$count = $result->user_count;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加