2017-09-01 56 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%,但可以很容易地修改。