如何将查询从mysql传递到laravel?

时间:2018-10-22 17:32:13

标签: mysql laravel eloquent

我在mysql SELECT TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age FROM employe where month(birthdate)=month(NOW())中的查询

获取该月的生日以及您的生日(从出生日期算起)。

在laravel中:

public function index()

{

    {


     $bird = DB::table('employe')

    ->whereraw('TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age FROM employe where month(birthdate)=month(NOW())') 

    ->select('employe.*')

    ->get();
    return response()->json(
        $bird->toArray()
    );

但是它会产生我错误

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS edad FROM employe where month(birthdate)=month(NOW())' at line 1 (SQL: select `employe`.* from `employe` where TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age FROM employe where month(birthdate)=month(NOW()))

1 个答案:

答案 0 :(得分:2)

  1. 由于您拥有$bird = DB::table('employe'),查询生成器已经知道要选择FROM的表,这就是为什么您不需要FROM employe->select('employe.*')

    < / li> 查询的
  2. TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS ageWHERE子句无关。我们需要将其移至查询的SELECT部分。

    $bird = DB::table('employe')
        ->select(DB::raw('*, TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age') 
        ->whereraw('MONTH(birthdate)=MONTH(NOW())')
        ->get();