简体   繁体   中英

Laravel 5 issue with executing query with DB::select

I've a query which perfectly works in phpmyadmin sql, but when I try to run the query in laravel 5 DB::select it gives me an error here is the code:

public function getCheckDueCurrentMonth()
    {
        $query = "SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) GROUP BY  SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC";

        $results = DB::select( DB::raw($query)); 
        return $results;


    }

here is the error:

QueryException in Connection.php line 761:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL 
 syntax; 
check the manual that corresponds to your MariaDB server version for the right syntax to 
use near 
'WHERE MAX(HISTORY_ID) GROUP BY SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC)' 
at line 1 (SQL: (SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN NOW() 
AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) 
GROUP BY SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC))

Use This

public function getCheckDueCurrentMonth()
        {
            $query = "SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) GROUP BY  SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC";

            $results = DB::Raw($query); 
            return $results;


        }

First, you're query is wrong. As I mentioned in my comment, queries can only have 1 WHERE. Join multiple clauses with AND, or OR.

$query = "SELECT * FROM history_card 
    WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)     
    AND MAX(HISTORY_ID) 
    GROUP BY  SERIAL_NUMBER 
    ORDER BY DUE_CAP_CHECK_DATE DESC";

I'm guessing you want only the last history_id, so you need to add that to the comparison:

$query = "SELECT * FROM history_card 
    WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) 
    AND history_id = MAX(HISTORY_ID) 
    GROUP BY  SERIAL_NUMBER 
    ORDER BY DUE_CAP_CHECK_DATE DESC";

DB::raw is usually when you're doing column comparison or MySQL functions with DB::select()->where().... , so you can drop it here.

$results = DB::select( $query);

事实证明,laravel 5在MySQL中使用“严格模式”,如果要禁用它,请转到MySQL中的database.php查找'strict' => true并将其设置为'strict' => false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM