Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel SQL select query where DateTimestamp contains this month and year

I'm trying to make a SQL query where I can check if the DateTimestamp contains this month and year.

A part of the query:

$leads = DB::table('leads') 
        ->leftJoin('invoices', function($join2) {
            $join2->on('leads.id', '=', 'invoices.lead_id');
        })
   ->where('invoices.chance', '!=', 0)
        ->where('invoices.updated_at', '=', date('m-Y')) //Check if DateTimestamp(updated_at) contains Year and month
            ->select('leads.*')

I tried it with date_parse, new DateTime(), but it didn't work. What am I doing wrong?

like image 261
JS-NL Avatar asked Sep 25 '22 23:09

JS-NL


People also ask

How do I select a specific month and year in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function. The syntax is as follows. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I get the current year in SQL query?

Just run these SQL queries one by one to get the specific element of your current date/time: Current year: SELECT date_part('year', (SELECT current_timestamp));

Which query is used to get the current data date?

GETDATE() function is mostly used to find the current Date. It will return the DATETIME data type. This means it will Return the Current date with the current Time.


1 Answers

You can use whereMonth() and whereYear() to achieve this:

$leads = DB::table('leads') 
    ->leftJoin('invoices', function($join2) {
        $join2->on('leads.id', '=', 'invoices.lead_id');
    })
    ->where('invoices.chance', '!=', 0)
    ->whereMonth('invoices.updated_at', '=', date('m')) // changed
    ->whereYear('invoices.updated_at', '=', date('Y')) // changed
    ->select('leads.*');
like image 118
Kirk Beard Avatar answered Oct 03 '22 07:10

Kirk Beard