簡體   English   中英

Laravel MySQL內部連接,還從另一個表中選擇一個特定字段

[英]Laravel mysql Inner join and also select a specific field from another table

我有以下查詢:

Ratings::join('users', 'movieratings.rated_by', '=', 'users.usr_id')
        ->where('rated_on', $movieId)
        ->orderBy('rated_at', 'desc')
        ->select('comment', 'rating', 'rated_as', 'rated_at', 'username')
        ->paginate(20);

這將獲取特定電影的所有反饋評分。 但是我還有另一個表,其中包含特定電影的總體好壞評分,唯一的問題是我無法同時查詢該表。

如果我執行另一個查詢,我會簡單地寫: Movie::where('movie_id', $movieId)->select('total_good_ratings', 'total_bad_ratings')->get(); 這將輸出例如“ 22,15 ”,但是是否有可能僅從特定行獲取兩列,然后在兩個表之間進行內部聯接並分頁結果?

謝謝

您可以使用包含好壞評分的表進行leftJoin,其中加入條件為影片的ID。

Ratings::join('users', 'movieratings.rated_by', '=', 'users.usr_id')
        ->leftJoin('movie', 'movie.id', '=', 'movieratings.rated_on')
        ->where('rated_on', $movieId)
        ->orderBy('rated_at', 'desc')
        ->select('comment', 'rating', 'rated_as', 'rated_at', 'username', 'total_good_ratings', 'total_bad_ratings')
        ->paginate(20);

我認為您可以嘗試以下方法:

Ratings::leftJoin('users', 'users.usr_id', '=', 'movieratings.rated_by')
        ->leftJoin('movie', 'movie.id', '=', 'movieratings.rated_on')
        ->where('movieratings.rated_on', $movieId)
        ->orderBy('movie.rated_at', 'desc')
        ->select('movieratings.comment', 'movieratings.rating', 'movieratings.rated_as', 'movie.rated_at', 'users.username', 'movieratings.total_good_ratings', 'movieratings.total_bad_ratings')
        ->paginate(20);

希望對您有幫助!

如果這可能有所幫助:

假設:

class Rating extends Model {
      public users() {
          $this->belongsTo(User::class, 'usr_id');
      }
      public movie() {
          $this->belongsTo(Movie::class, 'rated_on'); //Name looks odd, it should be movie_id if you are following standard conventions
      }
}

然后,您可以延遲/重新加載它們:

$ratings = Ratings::with([ "movie" => function ($query) {
        $q->select('total_good_ratings', 'total_bad_ratings');
     }])->where('rated_on', $movieId)
       ->orderBy('rated_at', 'desc')
       ->select('comment', 'rating', 'rated_as', 'rated_at', 'username',"rated_on")
       ->paginate(20);

您可以通過$ratings[X]->movie->total_good_ratings獲取電影信息(在循環中,這將是$rating->movie->total_good_ratings

雖然有點批評:

  1. total_good_ratings看起來像是一個派生屬性,因此它不應該首先存儲。 看來這是對良好收視率的一次計數。
  2. 在命名列和表時,應使用標准約定,例如,外鍵通常稱為<foreign table name in singular>_<foreign field name>例如user_idmovie_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM