I am trying to execute the following query in Eloquent ORM and cannot seem to execute the MySQL function -
$post = Post::where('slug', '=', $slug)->where('YEAR(created_at)', '=', $year)->first();
The exception I am getting is as follows - Message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(created_at)' in 'where clause'
SQL: SELECT * FROM `posts` WHERE `slug` = ? AND `YEAR(created_at)` = ? LIMIT 1
Bindings: array (
0 => 'placeholder',
1 => 2013,
)
So, basically, it is encapsulating the YEAR()
MySQL function as a column. Is there any way to do this without using a raw query?
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
A function can be called by specifying its name and parameter list wherever an expression of the appropriate data type may be used. To show how stored functions can be called, we'll use the simple stored function shown in Example 10-6.
mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.
When you create a website with Laravel, you can use Eloquent ORM to simplify managing your database. You can consider Eloquent ORM as a wrapper over the raw SQL queries and commands. Each Eloquent model is related to its corresponding database table.
To prevent Eloquent ORM from wrapping first variable with apostrophes, you can use DB:raw
function like:
$post = Post::where('slug', '=', $slug)
->where(DB::raw('YEAR(created_at)'), '=', $year)
->first();
And you'll get query:
SELECT * FROM `posts` WHERE `slug` = ? AND YEAR(created_at) = ? LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With