Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing MySQL functions to Eloquent ORM query

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?

like image 873
NightMICU Avatar asked Jan 10 '13 20:01

NightMICU


People also ask

Is query Builder faster than eloquent?

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.

How do you call a function in a MySQL query?

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.

What is mysql_query () function?

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.

Which ORM Laravel is used for handling DB queries?

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.


1 Answers

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
like image 110
ULazdins Avatar answered Oct 06 '22 23:10

ULazdins