Laravel使用DATE mysql函数查询Builder

时间:2017-06-28 18:59:31

标签: mysql laravel laravel-query-builder

您好我的laravel项目中有一个查询,它应该检索范围之间的日期。我的疑问是:

 $dateFrom = date("Y-m-d", strtotime($request->dateFrom));
      $dateTo = date("Y-m-d", strtotime($request->dateTo));
      $posts = DB::table('posts')->join('categories','posts.category_id','=','categories.id')->
                join('users','posts.user_id','=','users.id')
                ->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
                ->whereBetween('posts.created_at',[$dateFrom,$dateTo])
                ->get();

我想在posts.created_at列上使用DATE mysql_function,但我不知道怎么能这样做。以下查询不起作用:

$dateFrom = date("Y-m-d", strtotime($request->dateFrom));
      $dateTo = date("Y-m-d", strtotime($request->dateTo));
       $posts = DB::table('posts')->join('categories','posts.category_id','=','categories.id')->
                join('users','posts.user_id','=','users.id')
                ->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
                ->whereBetween('DATE(posts.created_at)',[$dateFrom,$dateTo])
                ->get();

我会很乐意得到帮助。最好的问候;)

2 个答案:

答案 0 :(得分:1)

更改->whereBetween('DATE(posts.created_at)'

->whereBetween(DB::raw('DATE(posts.created_at)'))

如果要在查询中添加一些原始表达式,可以使用laravel documentation中提到的DB::row方法

答案 1 :(得分:0)

尝试使用Carbon,如下所示:

use Carbon\Carbon;
...

$dateFrom = Carbon::parse($request->dateFrom);
$dateTo = Carbon::parse($request->dateTo);
$posts = DB::table('posts')
    ->join('categories','posts.category_id','=','categories.id')
    ->join('users','posts.user_id','=','users.id')
    ->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')
    ->whereBetween('posts.created_at',[$dateFrom,$dateTo])
    ->get();