2016-10-05 46 views
0

對於標題感到抱歉,但最好解釋它。我們已經構建了一個內部網絡應用程序,用於上傳視頻,以便像Instagram一樣評論和評論視頻。後端使用的是Laravel API。每天,我們需要給一個喊出來的是得到最像從昨天的關係是這樣的Laravel:如何根據需要計算行數的關係獲得結果

視頻 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'); 
    }... 

我知道我們可以做下面的一個,但檢索計數和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(); 

有沒有辦法我在我不需要計數的雄辯中,只需要最喜歡計數的視頻的編號,因爲我將使用編號來獲取視頻信息的集合。對於noob問題抱歉,只是想知道是否有任何方法可以正確有效地做到這一點,因爲我們期待着一些用戶。

下面是關於表的附加信息

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'); 
    }); 
+0

你試過左連接的基本實現嗎?如果沒有,請分享視頻表的表格結構,如表格。我理解的是,你也在跟蹤用戶的喜好。如果是這樣,每個像將被表示爲行。在這種情況下,您可以放置​​一個名爲''的列,並在插入時將其設置爲1。就像那樣,你可以用左連接和groupby來計算總數,而不是計數。需要更多的結構... – JTheDev

+0

對不起,伯爵也工作一樣。總和只是另一種方法。但無論如何,關係應該是正確的...... – JTheDev

+0

@JTheDev更新了表結構的問題 –

回答

0

的一個問題是存在的。你應該爲類似的表指定一個主鍵,我們可以唯一地識別每個喜好。我正在考慮它pk_like_id。然後應用下面的查詢。我假設像表中的videoId是引用視頻表的外鍵。 Video::,我用於指定視頻模型類。日期比較您可以根據您的功能進行更改。下面的查詢只會發現昨天發生的事情。不僅爲昨天的視頻。試試這個,它對我來說...

Video::select('video.id', DB::raw('COUNT(like.pk_like_id) as likecount')) 
     ->leftJoin('like', 'like.videoId', '=', 'video.id') 
     ->where('like.likeDate', '>=', Carbon::now()->subDay(1)->toDateString()) 
     ->where('like.likeDate', '<', Carbon::now()->toDateString()) 
     ->groupBy('video.id') 
     ->get(); 
+0

@德魯Adorator:任何運氣......? – JTheDev

+0

謝謝爲我工作! –

+0

@DrewAdorador:很高興聽到...享受:) – JTheDev