简体   繁体   中英

Laravel 5.6 eloquent whereDate and WhereRaw error

I am trying to find all records created today and start with a 1 for the column functional_id .

I get the below syntax error:

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 functional_id LIKE "1%"' at line 1 (SQL: select count(*) as aggregate from image_requests where date( created_at ) = 2019-01-24 00:00:00 and WHERE functional_id LIKE "1%")

My eloquent code:

$counter = ImageRequest::whereDate('created_at', $date)->whereRaw('WHERE functional_id LIKE "1%"')->count();

This should work:

$counter = ImageRequest::whereDate('created_at', $date)
    ->where('functional_id', 'like', '1%')
    ->count();

I think the issue is with the extra " . However, there's no need to use a whereRaw() in this case. A where() is more than enough and less proned for errors like this one :)

Edit: Based on your comment, if you want to check if the twelfth character is a 1 , the following should work:

$counter = ImageRequest::whereDate('created_at', $date)
    ->whereRaw('SUBSTRING(funtional_id, 12, 1) = 1')
    ->count();

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