前提・実現したいこと
環境
PHP 8.0.5
Laravel 6.20.32
mysql 8.0.25
questionsテーブルの回答上限数(limit)と
answersテーブルでカウント集計した回答数(answers_count)を
比較し回答上限数(limit)に達していないquestionsレコードを取得したい。
(リレーション先で集計した値とリレーション元が持つカラムの値を使って絞り込みを行いたい)
下記の例では questionsテーブルのid:2のレコードを取得したい。
questionsテーブル
id | limit | その他カラムは省略 |
---|---|---|
1 | 2 | |
2 | 2 |
answersテーブル
id | question_id | その他カラムは省略 |
---|---|---|
1 | 1 | |
2 | 1 | |
3 | 2 |
該当のソースコード
laravel
1class Question extends Model 2{ 3 public function answers() 4 { 5 return $this->hasMany('App\Models\Answer'); 6 } 7}
laravel
1model 2 3class Answer extends Model 4{ 5 public function question() 6 { 7 return $this->belongsTo('App\Models\Question'); 8 } 9}
laravel
1controller 2 3$questions = Question::withCount('answers') 4->having('answers_count','<','limit') 5->get(); 6dd($questions); 7 8'limit'を数字 2 など置き換えると期待通り取得できるので、リレーションは通っているようですが、 9リレーション元の'limit'で取得しようとすると下記の通り取得できません。 10上記のコードではquestionのid毎に設定している'limit'を取得出来ないのでしょうか?
上記のコンソールログ Illuminate\Database\Eloquent\Collection {#1553 #items: [] }
laravel
1controller //こちらも試してみました 2 3$questions = DB::table('questions') 4->join('answers', 'questions.id', '=', 'answers.question_id') 5->select('questions.id', 'questions.limit', DB::raw("count(answers.question_id) as answers_count")) 6->groupBy('questions.id') 7->where('answers.answers_count','<','questions.limit') 8->get(); 9dd($questions); 10 11answers_countカラムはないと叱られました。 12
上記のコンソールログ exception: "Illuminate\Database\QueryException" message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.answers_count' in 'where clause' (SQL: select `questions`.`id`, `questions`.`limit`, count(answers.question_id) as answers_count from `questions` inner join `answers` on `questions`.`id` = `answers`.`question_id` where `answers`.`answers_count` < questions.limit group by `questions`.`id`)"
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。