How to convert this queryto Laravel ORM - laravel

Hi guys I'm new learner Laravel.
I can not convert belowed SQL query, please help me to solve the problem.
SQL query is worked fine just I want to convert it Laraver Eloquent ORM.
select distinct u.*, d.user_id, r.region_name from users as u
left join devices as d on d.user_id = u.id
left join region as r on r.region_id = u.region_id
where d.user_id is null and u.`role` = 3
order by u.id asc

Here you go:
DB::table('users as u')
->select('u.*', 'd.user_id', 'r.region_name')
->distinct()
->leftJoin('devices as d', 'u.id', '=', 'd.user_id')
->leftJoin('region as r', 'u.region_id', '=', 'r.region_id')
->whereNull('d.user_id')
->where('u.role',3)
->oldest('u.id')
->get();

Related

Laravel - How to Convert MySQL query to Laravel Eloquent

I have MySQL query I want to convert to Laravel Eloquent
I have written the query in MySQL
SELECT a.transaction_number a.date, a.item_number, b.desc, a.variant_code, sum(a.quantity) AS quantity, a.cost
FROM `items_details` AS a
JOIN `items` AS b ON b.id = a.item_number
WHERE a.item_number = 0101010
GROUP BY a.variant_code
ORDER BY transaction_number, variant_code
Seems pretty simple.
DB::table('items_details as a')
->join('items b', 'b.id', '=', 'a.item_number')
->select([
'a.transaction_number',
'a.date',
'a.item_number',
'b.desc',
'a.variant_code',
DB::raw('sum(a.quantity) AS quantity'),
'a.cost'
])
->where('a.item_number', '=', 10101010)
->groupBy('a.variant_code')
->orderBy('transaction_number')
->orderBy('variant_code');
Note: Not Tested

SELECT COUNT in WHERE CLAUSE in Eloquent

I know that something similar was here some time ago,but it wasn't the same case and I can't just figure it out on myself.
I need to transform raw SQL query to Eloquent.
This query contains SELECT COUNT in WHERE clause, for simplicity I have this (may has not much sense) query :
SELECT u.column1, u.column2, u.column3, s.column1 FROM users u
LEFT JOIN salary s ON u.id = s.user_id
WHERE
(
SELECT count(cars_id) FROM cars WHERE cars.user_id = u.id
) = 0
AND u.city IN ("London","Paris")
I tried:
$columns = [
'users.column1',
'users.column2',
'users.column3',
'salary.column1'
];
$q = User::select($columns)
->leftJoin('salary', 'salary.user_id', '=', 'users.id')
->whereRaw(" (SELECT COUNT(cars_id) FROM cars WHERE cars.user_id = u.id) = 0 ")
->whereRaw("u.city IN ('London','Paris')")
->get();
But it doesn't return same results as raw SQL (SQL had 161 rows and Eloquent 154 rows).
Maybe you know how to transform this kind of query correctly to Eloquent?
Thanks
Based on your query I believe this should do it:
DB::table('users as u')
->select([ 'u.column1', 'u.column2', 'u.column3', 's.column1'])
->leftJoin('salary as s', 'u.id', '=', 's.user_id')
->leftJoin('cars as c', 'c.user_id', '=', 'u.id')
->whereIn('u.city', ['London', 'Paris'])
->havingRaw('count(c.id) = 0')
->get();
Please let me know.

I want to pass this query to Eloquent in laravel

I'm trying to make a query with eloquent, I try to get all the users who have one or more ads, taking into account that it is a one to many relationship (users to ads).
This query in general does what I want, but I do not know if it is well done and also how to pass it to Eloquent through the User model.
SELECT users.id, COUNT( anuncio.id ) AS 'total' FROM users
INNER JOIN anuncio ON users.id = anuncio.usuario_id WHERE
(SELECT COUNT( * ) FROM anuncio WHERE anuncio.usuario_id = users.id) >0
GROUP BY users.id ORDER BY total DESC
I have tried several ways that only return Builder to me.
For example:
$listas = new User;
$listas = $listas->join('anuncio','users.id','=','anuncio.usuario_id');
$listas = $listas->select(array('users.*', DB::raw('COUNT(anuncio.id) AS total')));
$listas = $listas->where(function($query) use ($listas){
$query->select(DB::raw('COUNT(anuncio.usuario_id)'))
->where('anuncio.usuario_id','=','users.id')
->groupBy('anuncio.usuario_id');
},'>','0');
$listas = $listas->orderBy('total','DESC')->paginate(48);
By any suggestion I will be very grateful.
Try with this
$listas = User::join('anuncio','users.id','=', 'anuncio.usuario_id')
->select('users.id',DB::raw("count(anuncio.id) as total"))
->groupby('users.id')
->having('total', '>', '0')
->orderby('total', 'desc')
->get();
Just use left join for this.
$users = DB::table('users')
->leftJoin('anuncio', 'users.id', '=', 'anuncio.usuario_id')
->get();
So Left Join will only select those result which has any match in anuncio table.

Big raw query to Eloquent

I have the following query:
select users.email, count(login_history.id) actions from users
left join group_memberships ON group_memberships.user_id = users.id
left join groups ON groups.id = group_memberships.group_id
left join organisation ON organisation.group_id = groups.parent_id
right join login_history ON login_history.user_id = users.id
where group_memberships.group_id = 564 AND ((MONTH(login_history.created_at) = MONTH(CURDATE()) AND YEAR(login_history.created_at) = YEAR(CURDATE())))
group by login_history.user_id
As I'd like to use scopes I need this query in Eloquent. I could use selectRaw and whereRaw and that should work, however would it be better to use Eloquent: Relationships for the Users model and this query? Is it even possible?
Any input much appreciated.
All of these db operations are well documented here. Except for maybe the left joins.
You do that like this (with a callback function):
->leftJoin('category_lang', function( $join ) {
$join->on( 'category_lang.category_id', '=', 'do_hta_dirs.hd_pag_ID' );
$join->on( 'category_lang.lang_id', '=', 'do_hta_dirs.hd_dID' );
$join->on( 'category_lang.active', '=', DB::raw( '1' ) );
})

Laravel ordering results of a left join

I am trying to replicate the below SQL in Laravels Eloquent query builder.
select a.name, b.note from projects a
left join (select note, project_id from projectnotes order by created_at desc) as b on (b.project_id = a.id)
where projectphase_id = 10 group by a.id;
So far I have:
$projects = Project::leftjoin('projectnotes', function($join)
{
$join->on('projectnotes.project_id', '=', 'projects.id');
})
->where('projectphase_id', '=', '10')
->select(array('projects.*', 'projectnotes.note as note'))
->groupBy('projects.id')
->get()
which works for everything except getting the most recent projectnotes, it just returns the first one entered into the projectnotes table for each project.
I need to get the order by 'created_at' desc into the left join but I don't know how to achieve this.
Any help would be much appreciated.
Your subquery is unnecessary and is just making the entire thing inefficient. To be sure though, make sure this query returns the same results...
SELECT
projects.name,
notes.note
FROM
projects
LEFT JOIN
projectnotes notes on projects.id = notes.project_id
WHERE
projects.projectphase_id = 10
ORDER BY
notes.created_at desc
If it does, that query translated to the query builder looks like this...
$projects = DB::table('projects')
->select('projects.name', 'notes.note')
->join('projectnotes as notes', 'projects.id', '=', 'notes.project_id', 'left')
->where('projects.projectphase_id', '=', '10')
->orderBy('notes.created_at', 'desc')
->get();

Resources