2017-09-01 38 views
1

我想強制兩篇文章之間1分鐘的差距,由同一用戶張貼。這是爲了防止意外的雙重發布,並希望減少垃圾郵件。兩篇文章之間強制1分鐘差距

現在我

public function canPostNewArticle() 
{ 
    $article = Article::where('user_id', $this->id)->latest()->first(); 
    if ($article == null) 
    { 
     return true; 
    } 
    $date = $article->created_at->timestamp; 
    $currentTime = Carbon::now()->timestamp; 

    $diff = ($currentTime - $date)/60; 
    return $diff > 1; 
} 

我使用這個函數創建一個新的文章之前入住User模型做這個。有一個更好的方法嗎。

回答

1

您可以簡單地使用以下查詢來決定用戶是否在一分鐘內發佈了文章。

public function canPostNewArticle() 
{ 
    return Article::where('user_id', $this->id) 
     ->where('created_at', '>=', Carbon::now()->subMinute()) 
     ->count() == 0; 
} 
1

另一種解決方案更簡單,看起來好一點在我看來是在數據庫調用中添加一個where子句,而不是先獲得一個計數(稍後創建的數量,然後削減時間戳),如果高於1,那麼你知道用戶在最近一小時內創建了一篇文章。

$oneHourAgo = strtotime() - 3600; 
$oneHourAgoTimestamp = date('dd-mm-yyyy hh:mi:ss', $oneHourAgo); 

return Article::where('user_id', $this->id)->andWhere('created_at', '>', oneHourAgoTimestamp)->count() == 0; 

我不是,如果我的第二個變量「oneHourAgoTimestamp」是具有正確的格式或不是100%,但可以很容易地修改。