如何通过使用碳日期时间扩展将数据库中的出生日期与当前月份匹配来获取数据?

时间:2015-07-24 05:19:06

标签: php mysql laravel laravel-5 php-carbon

我需要与我在Laravel 5中的SQL查询中给出的完全相同的结果。

SELECT * FROM `customers` WHERE MONTH(birthdate) = MONTH(NOW())    // get get current month's birthday

在我的控制器中,我有代码。

$customer['current_dob'] = Customers::where( DB::raw('MONTH(birthdate)','=','MONTH(NOW())'))->get();

型号:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    protected $table = 'customers';
    protected $fillable = array('fname','lname','email','mobile','birthdate','aniversary','gender','amount');
}

1 个答案:

答案 0 :(得分:2)

使用whereRaw

的好方案
// Get customer with birth date in current month
Customers::whereRaw('MONTH(birthdate) = MONTH(NOW())')->get();

// Get customer with birth date in a specific month
$month = Carbon\Carbon::now()->month; // Current month with Carbon
Customers::whereRaw('MONTH(birthdate) = ?', [$month])->get();