2017-07-31 46 views
0

我有以下查詢選擇一個特定的領域:Laravel MySQL的內部聯接,也從另一個表

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」但有可能只從一個特定的行獲取兩列然後做之間的內部連接兩個表和分頁的結果?

感謝

+0

爲什麼不使用普通的Eloquent關係而不是聯接?這種方式更容易。 – apokryfos

+0

@apokryfos主要是因爲我不確定當我調用一些laravels輔助函數時會發生什麼。只要他們在大多數時間安全,我發現編寫原始sql更容易 – user2722667

回答

1

你可以做一個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); 
+0

這意味着可以在未評級電影的情況下進行評級。 – apokryfos

1

我想你可以試試這個:

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); 

希望這有助於爲你!

0

在情況下,這可能會有所幫助:

假設:

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 
     } 
} 

然後你可以偷懶/ eaher加載它們:

$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

有點批評que雖然:

  1. total_good_ratings看起來像它是派生屬性,所以它不應該被存儲在第一個地方。這似乎是好評率的計數。
  2. 您應該在命名列和表時使用標準約定,例如外鍵通常被稱爲<foreign table name in singular>_<foreign field name>示例user_idmovie_id