I am using Laravel Framework 6.16.0.
I have the following sql query:
SELECT DISTINCT
`companies`.*
FROM
`companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
`trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
companies.symbol
FROM
`companies`
LEFT JOIN articles a ON a.companies_id = companies.id
WHERE
a.created_at >= 2020-11-12
ORDER BY
created_at
DESC)
ORDER BY
transaction_date
DESC
I have created the following eloquent query:
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
->orderBy('transaction_date', 'desc')
->distinct()
->get('symbol');
However, I am not sure how to pack the in my eloquent query to get all the symbol back that should be excluded.
I highly appreciate your replies!
You should try something like this:
$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', $date)
->whereNotIn('companies.symbol', function ($q) use ($date) => {
$q->select('companies.symbol')
->from('companies')
->leftJoin('articles', 'articles.companies_id', 'companies.id')
->where('articles.created_at', '>', $date)
->distinct()
->get()
})
->orderBy('transaction_date', 'desc')
->distinct()
->get();
It will provide a similar query as you mentioned.
Reference from here.
Also, you can read how to write sub Query from Laravel docs.
Check this one more good answer for that what you need.
Related
I'm trying to conver this SQL query to Laravel query.
SELECT count(*) FROM (SELECT order_id FROM table1 WHERE app_process='7' AND ( service_type='lite' OR ((end_time-".time().")/86400)>'0') ) a INNER JOIN (SELECT order_id FROM table2 WHERE process='1' AND amount>'0' GROUP BY order_id) b ON a.order_id=b.order_id
I almost success(?) to converting but I don't know how to convert the time part.
end_time-".time().")/86400
what I converted
Db::table('table1 as A')
->select('A.order_id')
->where('A.app_process', '=', '7')
->where('A.service_type', '=', 'lite')
->orWhere('A.end_time', '>', '0') <== problem here!!
->join(Db::raw('(select order_id from table2 where process = 1 and amount > 0 group by order_id) B'), 'B.order_id', '=', 'A.order_id')
->count();
Could someone help me to solve the time part?
As far as I understand the query, it just checks if end_time is in the future. So you can just do the following:
->orWhere('A.end_time', '>', now())
now() is a Laravel helper that returns the current datetime.
I finally found out the right query. It turns out the problem was not only just 'time()' but also the wrong converted query.
I post this maybe help someone.
Db::table('table1 as A')
->leftJoin('table2 as B', 'A.order_id', '=', 'B.order_id')
->where('A.app_process', '=', '7')
->where(function($query){
$query->where('A.service_type', '=', 'lite')->orWhere('A.end_time', '>', time());
})
->where('B.process', '=', '1')
->where('B.amount', '>', '0')
->distinct()
->count('A.order_id');
try this I think it helps you
Db::table('table1 as A')
->select('A.order_id')
->where([['A.app_process', '=', '7'],['A.service_type', '=', 'lite']])
->orWhere('A.end_time', '>', now())
->join(Db::raw('(select order_id from table2 where process = 1 and amount > 0 group by order_id) B'), 'B.order_id', '=', 'A.order_id')
->count();
i am having this query with me which needs to be written in the eloquent form on internet not able to find exact solution for my problem.
SELECT
query_id, t1.time, result, platform_id
FROM
query_logs t1
WHERE
t1.time = (SELECT
MAX(time)
FROM
query_logs t2
WHERE
t1.query_id = t2.query_id);
i tried writing it as below i used query_Logs as model to my controller:
$bmdata = Query_Logs::select('query_id', 'time','result','platform_id')
->where('time', function($q){
$q->from('query_logs')
->selectRaw('max(time)')
->where('query_id', '=', 'query_id')
})
->get();
Can you guys help me with the same.
Use this:
$bmdata = Query_Logs::select('query_id', 'time', 'result', 'platform_id')
->where('time', function($q) {
$q->from('query_logs as t2')
->selectRaw('max(time)')
->whereColumn('t2.query_id', '=', 'query_logs.query_id');
})->get();
I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();
I'd like to get the difference between two dates on two tables. The uploads.published_at compared to the completed_guides.created_at
I keep getting an error which says:
SQLSTATE[42000]: Syntax error or access violation: 1582 Incorrect parameter count in the call to native function 'datediff' (SQL: select users.*,completed_guides.created_at as completed_at,uploads.published_at,datediff(HOUR, published_at, completed_at) from `users` inner join `uploads` on `users`.`id` = `uploads`.`user_id` inner join `completed_guides` on `uploads`.`id` = `completed_guides`.`upload_id` where `completed_guides`.`upload_id` = 2839 limit 10)
Here is my code. Any help would be appreciated.
$select = [
'users.*',
'completed_guides.created_at as completed_at',
'uploads.published_at',
'datediff(HOUR, published_at, completed_at) as date_diff'
];
return User::select(DB::raw(join(',', $select)))
->join('uploads', 'users.id', '=', 'uploads.user_id')
->join('completed_guides', 'uploads.id', '=', 'completed_guides.upload_id')
->where('completed_guides.upload_id', $this->id)
->take(10)
->get();
You can use Laravel Query Builder's whereRaw() like this:
return User::select(DB::raw(join(',', $select)))
->join('uploads', 'users.id', '=', 'uploads.user_id')
->join('completed_guides', 'uploads.id', '=', 'completed_guides.upload_id')
->where('completed_guides.upload_id', $this->id)
->whereRaw('datediff(uploads.published_at, completed_guides.completed_at) as date_diff')
->take(10)
->get();
To set the format of date you can use SQL method - date_format(date, format) like this:
->select(DB::raw("DATE_FORMAT(date_diff, '%b %d %Y %h:%i %p') as formatted_date_diff"));
See more about SQL Date Format
Hope this helps!
The one with units, is timestampdiff, not datediff.
timestampdiff(HOUR, published_at, completed_at) as date_diff
To make the report i need to write a join query. I wrote the join query in sql now, i need to write the same query in laravel 5.2.
My sql query is given below.
SELECT a.accountID, a.deviceID, b.description, a.timestamp, a.latitude, a.longitude, a.speedKPH as speed, a.heading, a.altitude, a.address, a.distanceKM as distance, a.odometerKM as odometer, a.IbatVolts, a.EbatVolts, a.ITempr, a.fuelLevel, a.inputState, a.IgnRuntime, a.GPSFixType, a.GPSPDOP, a.AlertType, a.speedLimitKPH, a.isTollRoad
FROM eventdata as a, device as b
WHERE a.deviceID = '$deviceID'
AND a.accountID = '$accountID'
AND a.timestamp >= $dt1
AND a.timestamp <= $dt2
AND a.deviceID=b.deviceID
ORDER BY timestamp DESC
and i tried to write it in laravel also. the query is given below
DB::table('device as b')
->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID')
->where('a.deviceID', '=', '$deviceID')
->where('a.accountID', '=', '$accountID')
->where('a.timestamp', '>=', '$dt1')
->where('a.timestamp', '<=', '$dt2')
->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp',
'a.latitude', 'a.longitude', 'a.speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.AlterType', 'a.speedLimitKPH', 'a.isTollRoad')->get():
Is this right? Can anyone tell me and help me to write the correct query.
The join syntax in laravel 5.2 is:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
and you are using the same. In case you are facing any issue than you can print the raw sql query by using:
DB::enableQueryLog();
// Your query
$queries = DB::getQueryLog();
print_r($queries); // it will print raw sql query in prepared statement style