0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】リレーションしている数の検索

Posted at

状況

リレーション件数を検索にかけたい。
どういうことかというと、
User->post()->countがあったとして、
ユーザごとに何件投稿したかが表示されるようになっている。
その件数を検索したい。

問題

検索の時はwhereを使うもんだと思っていたのだが、
カラム検索ではないので使えないらしい。
where('カラム', '検索ワード');

countをカラムにしてしまおうと思った。
selectRaw('count(*) as cnt')とするとcntをカラムとして使えるっぽいので、

selectRaw('count(*) as cnt')
    ->where('cnt', '$request->xxx');

これをリレーション先で指定するから

whereHas('posts', function($query) use($q){
    $query->selectRaw('count(*) as cnt')
          ->where('cnt', '$request->xxx')
          ->groupBy('cnt');
});

これでもダメみたい。。
全てのPostの件数を取得するので、
User1->post = 3
User1->post = 10
User1->post = 30
とかだと、countで43になっちゃうのではないか。

あまり使ったことのないSQLの知識を使いながら奮闘しましたけど、できませんでした。

hasメソッド?

hasメソッドを使えば簡単らしい。
$query->has('posts', 'リクエスト');
これだけです。

$queryごとにPostの件数を取得してリクエストと照らし合わせてくれる。
簡単すぎた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?