Cakephp3+Mysqlの環境で、Cakephpから相関サブクエリを実行する際、結果がnullになります。
発行したいSQL
SQL
1SELECT main_follows.follower_shop AS `id`, 2(SELECT (AVG(sub_follows.rating)) AS `rating` FROM follows sub_follows 3 WHERE sub_follows.follower_shop = main_follows.follower_shop GROUP BY sub_follows.follower_shop ) 4AS `average_all` FROM follows main_follows WHERE main_follows.follow = 1 5 6--結果 7--"id": "1", "average_all": 2.6641 8--"id": "1", "average_all": 3.2215 9--"id": "1", "average_all": 3.5427 10
CakePHPのコード(結果はaverage_allがnullになる)
PHP
1$FollowsTable = TableRegistry::getTableLocator()->get('follows'); 2//メインクエリ 3$main_query = $FollowsTable->find()->from(['main_follows'=>'follows']) 4 ->where(['main_follows.follow'=>'1']) 5 ->select(['id'=>'main_follows.follower_shop']); 6 7//サブクエリ 8$sub_query = $FollowsTable->find()->from(['sub_follows'=>'follows']) 9 ->where(['sub_follows.follower_shop'=>'main_follows.follower_shop']); //① 10$sub_query = $sub_query->select(['rating' => $sub_query->func()->avg('sub_follows.rating')]) 11 ->group(['sub_follows.follower_shop']); 12 13$main_query = $main_query->select(['average_all' => $sub_query]); 14 15//結果 16//"id": "1", "average_all": null 17//"id": "1", "average_all": null 18//"id": "1", "average_all": null
①の'main_follows.follower_shop'がメインクエリから値を取得できていないように思えますが、原因がわかりません。
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。