kunal
kunal

Reputation: 4248

Convert SQL query to laravel 5.2?

Can anyone help me how to convert the SQL query to Larvel 5.2

First query (for current month)

SELECT 
    * 
FROM 
    customer_allocations 
WHERE 
    YEAR(date) = YEAR(NOW()) AND MONTH(date) = MONTH(NOW());

Second query (for current week)

SELECT 
    * 
FROM 
    customer_allocations 
WHERE 
    WEEKOFYEAR(date) = WEEKOFYEAR(NOW());

Third query (for current day)

SELECT 
    * 
FROM 
    customer_allocations 
WHERE 
    YEAR(date) = YEAR(NOW()) AND 
    MONTH(date) = MONTH(NOW()) AND 
    DAY(date) = DAY(NOW());

These SQL queries run successfully in phpmyadmin but I want to implement in laravel can anyone help me.

I have tried to convert these queries, but I get an error message on this line of code:

CustomerAllocation::where([YEAR('date'),'=',YEAR(NOW()),MONTH('date'),'=',
                            MONTH(NOW())])->get();

This is the error:

Call to undefined function "App\Http\Controllers\YEAR()"

Upvotes: 0

Views: 154

Answers (1)

Nerea
Nerea

Reputation: 2147

Change

CustomerAllocation::where([YEAR('date'),'=',YEAR(NOW()),MONTH('date'),'=',MONTH(NOW())])->get()

to

CustomerAllocation::whereRaw("YEAR(date) = YEAR(NOW())")->whereRaw("MONTH(date) = MONTH(NOW())")->get()

Use whereRaw()where you want put check custom condition like you want to do.

Upvotes: 1

Related Questions