【发布时间】:2016-10-05 01:23:47
【问题描述】:
对不起标题,但最好解释一下。我们已经构建了一个内部网络应用程序,可以上传视频,您可以在其中评论和喜欢视频,就像 Instagram 一样。后端使用 Laravel API。每天我们需要为昨天获得最多赞的10个视频点赞,关系就是这样
视频 - 有很多喜欢
喜欢 - 属于一个视频
class Stage extends Model
{
public function likes()
{
return $this->hasMany('App\likes', 'id');
}...
class Likes extends Model
{
public function likes()
{
return $this->belongsTo('App\Video', 'videoId');
}...
我知道我们可以执行以下操作,但会同时检索 count 和 videoId
DB::table('likes')
->select(DB::raw("
videoId,
count(*) as LikeCount"))
->where('createDate', '>=', Carbon::now()->subDay(1)->toDateString())
->where('createDate', '<', Carbon::now()->toDateString())
->groupBy('videoId')
->get();
有没有办法以雄辩的方式实现这一点,我不需要计数,只需要最喜欢计数的视频的 id,因为我将使用 id 来获取视频信息的集合。很抱歉这个菜鸟问题,只是想知道是否还有正确有效的方法,因为我们期待大量用户。
这里是关于表格的附加信息
Schema::create('video', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('userId')->unsigned();
$table->string('name',255)->nullable();
$table->text('description')->nullable();
$table->string('status', 50)->nullable();
$table->text('video')->nullable();
$table->dateTime('createDate')->nullable();
$table->dateTime('upStageDate')->nullable();
$table->foreign('userId')->references('userId')->on('user')- >onDelete('cascade');
});
Schema::create('like', function (Blueprint $table) {
$table->integer('videoId')->unsigned();
$table->integer('userId')->unsigned();
$table->datetime('likeDate')->nullable();
$table->foreign('userId')->references('userId')->on('user')->onDelete('cascade');
$table->foreign('videoId')->references('id')->on('video')->onDelete('cascade');
});
【问题讨论】:
-
你尝试过左连接的基本实现吗?如果没有,请分享视频表的表结构,如表。我的理解是,您也在根据用户跟踪喜欢。如果是这样,每个喜欢都将表示为行。在这种情况下,您可以放置一个名为“喜欢”的列,并在插入时将其设置为一个。像这样,您可以使用左连接和 groupby 进行总和,而不是计数。需要更多结构...
-
对不起,count 也一样。 Sum 只是另一种方法。但无论如何,关系应该是正确的......
-
@JTheDev 用表格结构更新了问题
-
我可以知道
stage是什么,还是like表中的videoId与video表直接相关? -
@JTheDev 抱歉更正了表格引用