Need to convert raw sql to eloquent query builder - laravel

I need to convert the following sql query to eloquent query builder.
select * from projects
inner join assigned_projects on projects.id = assigned_projects.project_id
where assigned_projects.user_id=9;
where projects and assigned_projects are in many to many relation. Please help me figure it out.

$project = DB::table('projects')
->join('assigned_projects' , 'projects.id' , '=', 'assigned_projects.project_id')
->where('assigned_projects.user_id', '=', 9)
->get();

Related

How to use WITH clause in Laravel Query Builder

I have SQL query (see example).
But I can't find a way how I can write it in Query Builder.
Do you have any ideas how is it possible?
WITH main AS (
SELECT id FROM table1
)
SELECT * FROM table2
WHERE
table2.id IN (SELECT * FROM main)
I want to get format like:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
but for WITH
Laravel has no native support for common table expressions.
I've created a package for it: https://github.com/staudenmeir/laravel-cte
You can use it like this:
$query = DB::table('table1')->select('id');
$result = DB::table('table2')
->withExpression('main', $query)
->whereIn('table2.id', DB::table('main')->select('id'))
->get();
Query builder has to be compatible with multiple database engines (mysql, postgresql, sql lite, sql server) and as such only offers support for common functionality.
Assuming your query returns data, you may be able to use the DB:select() method to execute a raw query.
$data = DB::select('WITH main AS (SELECT id FROM table1), SELECT * FROM table2 WHERE table2.id IN (SELECT * FROM main)');
The DB:select method also accepts a second parameter for using named bindings.
Alternatively there are packages available such as laravel-cte that will add the functionality to Eloquent/ Query Builder.

Convert sql query to query builder using laravel 5.4

Hi I my try to convert SQL query to Query Builder. My Sql query below like this
SELECT exclusive_distributor_opens.distribution_code,exclusive_distributor_opens.distribution_name,exclusive_item_opens.item_code,exclusive_item_opens.item_name,SUM(exclusive_budget_items_details.dealer_contribution) as Total,exclusive_distributor_opens.date
FROM exclusive_budget_masters
JOIN exclusive_distributor_opens
ON exclusive_budget_masters.distributor_id=exclusive_distributor_opens.id
JOIN exclusive_budget_items_details
ON exclusive_budget_masters.distributor_id=exclusive_budget_items_details.budget_master_id
JOIN exclusive_item_opens
ON exclusive_budget_items_details.item_id=exclusive_item_opens.id
GROUP BY (exclusive_distributor_opens.distribution_code)
HAVING exclusive_distributor_opens.date BETWEEN '2018-12-19' AND '2018-12-19'
ORDER BY exclusive_distributor_opens.distribution_code DESC
2.My Query Builder Query like this
$results = DB::table('exclusive_budget_masters')
->join('exclusive_distributor_opens', 'exclusive_budget_masters.distributor_id', '=', 'exclusive_distributor_opens.id')
->join('exclusive_budget_items_details', 'exclusive_budget_masters.distributor_id' ,'=', 'exclusive_budget_items_details.budget_master_id')
->join('exclusive_item_opens', 'exclusive_budget_items_details.item_id', '=', 'exclusive_item_opens.id')
->select('exclusive_distributor_opens.distribution_code', 'exclusive_distributor_opens.distribution_name','exclusive_budget_items_details.customar_contribution', DB::raw('SUM(exclusive_budget_items_details.customar_contribution) As Total'))
->whereBetween('exclusive_distributor_opens.date', array('2018-12-19', '2018-12-19'))
->groupBy('exclusive_distributor_opens.distribution_code', 'exclusive_distributor_opens.distribution_name','exclusive_budget_items_details.customar_contribution')
->orderBy('exclusive_distributor_opens.date', 'DESC')
->get();
My Query Output Result Comes like this:
But My Expected Result looks like this:
Please anybody help me.
Why do you expect this to work?
Select part is missing or wrong:
exclusive_item_opens.item_code missing
exclusive_item_opens.item_name missing
exclusive_distributor_opens.date missing
SUM Total column is wrong:
SUM(exclusive_budget_items_details.dealer_contribution) as Total vs
DB::raw('SUM(exclusive_budget_items_details.customar_contribution) As Total')
Your builder query looks like this:
SELECT `exclusive_distributor_opens`.`distribution_code`,
`exclusive_distributor_opens`.`distribution_name`,
`exclusive_budget_items_details`.`customar_contribution`,
Sum(exclusive_budget_items_details.customar_contribution) AS Total
FROM `exclusive_budget_masters`
INNER JOIN `exclusive_distributor_opens`
ON `exclusive_budget_masters`.`distributor_id` =
`exclusive_distributor_opens`.`id`
INNER JOIN `exclusive_budget_items_details`
ON `exclusive_budget_masters`.`distributor_id` =
`exclusive_budget_items_details`.`budget_master_id`
INNER JOIN `exclusive_item_opens`
ON `exclusive_budget_items_details`.`item_id` =
`exclusive_item_opens`.`id`
WHERE `exclusive_distributor_opens`.`date` BETWEEN ? AND ?
GROUP BY `exclusive_distributor_opens`.`distribution_code`,
`exclusive_distributor_opens`.`distribution_name`,
`exclusive_budget_items_details`.`customar_contribution`
ORDER BY `exclusive_distributor_opens`.`date` DESC

Laravel Left Join Query

I am using laravel 5.3 and I have some left join query with error in laravel query method.
This is my normal query
SELECT bran.branchName,sch.schoolName From m_schoolbranch bran
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001';
And this is my new laravel Query
DB::table('m_schoolbranch')
->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo')
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();
In these query I need to match two column in table m_students so I put like this
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
But i show error...
Tables in the query need to have unique names, otherwise the DB has no way of knowing which m_schoolbranch should be used when evaluating m_schoolbranch.schoolNo.
You could use unique table aliases in your join statements but I recommend using multiple conditions on the join. Just like you use in your original SQL query. See here: https://stackoverflow.com/a/20732468/4437888
DB::table('m_schoolbranch')
->join('m_students', function($join)
{
$join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo');
$join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo');
})
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();

subquery with distinct clause in query builder/laravel

SELECT * FROM `movie_list`
WHERE `movie_id` IN
(SELECT DISTINCT movie_id FROM `movie_genre` where genre_id in (12,18,53))
AND rated IN
('Not Rated','N/A')
How can i convert the above to a query builder syntax:
$movies = DB::table('movie_list')
->whereIn('movie_id',function($query){
$query->select.....
})->get();
I have the inner one: it goes like this:
DB::table('movie_genre')
->whereIn('genre_id', array(12,18,53))
->distinct()
->get(array('movie_id'));
How do i use this result with the rest of my query?
You could do this alot smoother with Eloquent Models, but assuming you don't have your models setup, this should do the trick (untested)
$ids = DB::table('movie_genre')
->whereIn('genre_id', [12,18,33])
->distinct()
->get(['movie_id'])
->toArray();
$movies = DB::table('movie_list')
->whereIn('movie_id', array_values($ids))
->get();

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