Laravel:创造雄辩的范围


Laravel: creating eloquent scope

各位开发者好,

我正在练习一点雄辩,遇到了一些麻烦。我的令牌表现在看起来像这样:

Table Token
email (VARCHAR 255)
token (VARCHAR 255)
expires (VARCHAR 255)  // this should probably be int.. 
created_at timestamp

在我的令牌模型中,我正在构建一个范围来检索所有过期令牌

public function scopeExpired($query)
{
    return $query->where('created_at', '<', date('Y-m-d H:i:s', time()-   ('expires'*60)));
}

这几乎可以达到目的,但是它忽略了('expires'*60)。如果我把'expires'替换成一个数字,比如30,它可以很好地工作。

我的问题基本上归结为:我如何使用到期列对应行的值?

非常感谢任何帮助!

问候,Pwnball

所以,我解决了这个问题!我没有设法获得相应列的值,但我认为将令牌的过期时间存储在配置中是明智的。

现在我使用这段代码来定义作用域,它工作得很好!我从令牌表中删除了'expires'列,并将其替换为:

type varchar 50

看到我知道我在代码的每个特定点使用什么类型的令牌,这解决了困境,并导致更容易维护的代码!双赢!

public function scopeExpired($query, $type)
{
    $expires = Config::get('app.tokenExpiration.'.$type, 30);
    return $query->where('created_at', '<', date('Y-m-d H:i:s', time()-($expires*60)));
}

MySQL问题的解决方案(PostreSQL会更容易一点,其他引擎相应):

public function scopeExpired($query)
{
  return $query->where('created_at', '<', 
     DB::raw('timestampadd(hour, -expires, now())'
  );
}

使用查询生成器的whereRaw()方法编写原始SQL,即

return $query->whereRaw("`created_at` < DATE_SUB(NOW(), INTERVAL `expires` MINUTE)");
MySQL 3.23 +