story ks
story ks

Reputation: 850

laravel how can convert sql to laravel sql

i find data between date current from database has start and end date from 2 attribute

this is database

and this is sql code

select * from period WHERE
priceId = 1788749 AND
'2018-05-07 02:00:00' BETWEEN startPeriod AND endPeriod

but,i don't know how i can use in laravel

i'm try

$now = Carbon::now()->toDateTimeString();
$prod =DB::table('period')->where('priceId','=', 1788749)
->wherebetween($now, ['startPeriod', 'endPeriod'])
->get();

Upvotes: 1

Views: 64

Answers (2)

Winston Fale
Winston Fale

Reputation: 1346

Read the documentation here https://laravel.com/docs/5.6/eloquent

Almost laravel application use eloquent as their sql package. The one you use is a DB facade which is okay also.

if translate to eloquent your query will be:

$prod = Period::where('priceId',1788749)->where('startPeriod','>',$now)->where('endPeriod','<',$now)->get()

startPeriod and endPeriod should date when you migrate it in the database

i dont think you can use whereBetween because it required as a first params is the column name of the table not a dynamic value

Upvotes: 1

Maaz Ali
Maaz Ali

Reputation: 83

You can take a look at the carbon's diffInDays/diffInMonths/diffInYears (according to your requirements) function for getting the difference between two dates.

Make sure to parse the date according to the carbon format using this. $convertedDate = Carbon::parse($yourDate);

http://carbon.nesbot.com/docs/

Happy Coding

Upvotes: 1

Related Questions