Twitterもどきを作成しています。
自分がいいねした投稿だけのデータをページネーションとして取得したいのですが、
->where('posts.is_liked', '=', '1')
部分で下記エラーが表示されてしまいます。
元のテーブルに無いカラムで、一時的に追加しているカラムはwhereでの絞り込みってできないのでしょうか?
少々この場合の別の絞り込み法がわからず教えて頂きたいです、、、
試したこととしては、他のメソッド内で同じようなことをしていて
->where('posts.user_id', '=', $user->id)
こちらはうまくいきました。おそらくuser_idは元テーブルのカラムに存在しておりまして、一時的なカラムとして追加していないためかと思います。
よろしくお願いいたします。
PHP
1 // $userはcontrollerから呼び出す引数です。 2 // ログインユーザーがいいねしている投稿データを取得 3 public function getLikedPost($user) 4 { 5 $count_like = DB::table('likes') 6 ->selectRaw('post_id, count(*) as `count`') 7 ->groupBy('post_id'); 8 9 $new_post = new Post(); 10 11 $liked_posts = $new_post->newQuery() 12 ->leftJoin('likes', function ($query) use ($user) { 13 // いいねされた状態のものを結合 14 // 結合前の結合条件を指定 15 $query->on('posts.id', '=', 'likes.post_id'); 16 // 結合後の条件でデータ絞り込み 17 // (ログインしているユーザのいいね) 18 $query->where('likes.user_id', $user->id); 19 }) 20 ->leftJoinSub($count_like, 'count_like', function ($join) { 21 $join->on('posts.id', '=', 'count_like.post_id'); 22 }) 23 ->selectRaw('posts.*, IFNULL(count_like.`count`, 0) as `count`, posts.id = IFNULL(likes.post_id, 0) as is_liked') 24 ->where('posts.is_liked', '=', '1') 25 ->orderBy('created_at', 'desc') 26 ->paginate(3); 27 // ->get(); 28 29 // リレーション 30 $liked_posts->load('user'); 31 32 // 投稿に紐づくコメント数を取得 33 $liked_posts->each(function ($post) { 34 $post->comment_count = $post->comments()->count(); 35 }); 36 37 return $liked_posts; 38 }
エラー
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.is_liked' in 'where clause' (SQL: select count(*) as aggregate from `posts` left join `likes` on `posts`.`id` = `likes`.`post_id` and `likes`.`user_id` = 1 left join (select post_id, count(*) as `count` from `likes` group by `post_id`) as `count_like` on `posts`.`id` = `count_like`.`post_id` where `posts`.`is_liked` != 1)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/15 15:47 編集