Laravel 5.2使用雄辩的方法获取每行数据的date_diff

时间:2019-06-09 03:41:05

标签: php mysql eloquent laravel-5.2

我想获取与今天的日期的日期差,并在查询数据库的每一行以计算天数时设置为参考。如何以雄辩的方式构建它?谢谢!

$query ="SELECT unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff from users WHERE trial=1";
$result=mysql_query($query) or die(mysql_error());

while($row=mysql_fetch_assoc($result)) 
{ 
 $diff= $row['time_diff']
}

1 个答案:

答案 0 :(得分:1)

您可以在laravel Query Builder中使用selectRaw

DB::table('users')
->selectRaw('unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff')
->where('trial',1)
->get();

或者您要使用Eloquent

Model::select(DB::raw('unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff'))
->where('trial',1)
->get();