繁体   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