Sub-queries in Laravel - laravel

I have a query in MySQL
SELECT * FROM group_recordings WHERE id IN ( SELECT MAX(id) FROM group_recordings GROUP BY time_span )
there is a sub-query in "IN" operator, I want to convert this query in laravel eloquent, I have GroupRecording Model. Anyone help me with that

I think the Laravel style of such query will be,
GroupRecording::whereIn('id', function($query) {
$query->selectRaw('MAX(id)')
->from('group_recordings')
->groupBy('time_span');
})
->where('time_span', '>', $recording->time_span)
->get();

Related

GraphQL Where Select Sub Query

These day, i have studied GraphQL with Laravel framework, Lighthouse Library.
I have tried to do kind of SELECT Query.
As a result, I wonder GraphQL can select below SQL Query
SELECT * FROM TABLE_A WHERE type=1 AND chart_id=(SELECT id FROM TABLE_B WHERE phone='0000~~')
I expect, Client first get result from this query.
SELECT id FROM TABLE_B WHERE phone='0000~~'
And then Do Second query, i think i can get a result.
But i wonder I can get result from 1 request. Thanks.
You can try following
$phoneNumber = '0000~~';
$data = DB::table('tableA')->where('type',1)
->whereIn('chart_id',function($query) use ($phoneNumber) {
$query->select('id')
->from('tableB')
->where('phone', '=',$phoneNumber);
})->get();
If there is relationship between tableA and tableB you can do following
TableA::where('type',1)
->whereHas('tableBRelationshipName', function ($q) use ($phoneNumber) {
$q->select('id')
$q->where('phone','=',$phoneNumber);
})->get();

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.

Converting a raw query to Laravel query builder

I have the following MySQL query which fetches a list of the last 9 authors to write a post and lists them in order of the date of the last post they wrote.
It's working properly but I'd like to re-write it using the Laravel Query Builder. Here is the query at the moment:
$authors = DB::select("
SELECT
`a`.`id`,
`a`.`name`,
`a`.`avatar`,
`a`.`slug` AS `author_slug`,
`p`.`subheading`,
`p`.`title`,
`p`.`slug` AS `post_slug`,
`p`.`summary`,
`p`.`published_at`
FROM
`authors` AS `a`
JOIN
`posts` AS `p`
ON `p`.`id` =
(
SELECT `p2`.`id`
FROM `posts` AS `p2`
WHERE `p2`.`author_id` = `a`.`id`
ORDER BY `p2`.`published_at` DESC
LIMIT 1
)
WHERE
`a`.`online` = 1
ORDER BY
`published_at` DESC
LIMIT 9
");
I understand the basics of using the query builder, but there doesn't appear to be anything in the Laravel docs that allows for me to JOIN a table ON a SELECT.
Can anyone suggest a way that I can write this query using the Laravel Query builder, or perhaps suggest a way that I can rewrite this query to make it easier to structure with the query builder?
Try to do like this
$data = DB::table('authors')
->select(
'a.id',
'a.name',
'a.avatar',
'a.slug AS author_slug',
'p.subheading',
'p.title',
'p.slug AS post_slug',
'p.summary',
p.published_at')
->from('authors AS a')
->join('posts AS p', 'p.id', '=', DB::raw("
(
SELECT p2.id FROM posts AS p2
WHERE p2.author_id = b.id
ORDER BY p2.published_at
DESC LIMIT 1
)"))
->where('a.online', 1)
->limit(9)
->orderBy('p.published_at', 'desc')
->get();

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();

eloquent where not in query?

I'm trying to build the following sql query with eloquent. The query gives me all records from table_a which are in the list of ids and do not appear in table_b.
select * from table_a
where id in (1,2,3)
and id not in
(select tablea_id from table_b
where tablea_id in (1,2,3))
So how do I do it in eloquent ? I want to avoid using a raw query.
//does not work
TableA::whereIn('id',$ids)
->whereNotIn('id', TableB::select('tabla_id')->whereIn($ids));
To run a subquery you have to pass a closure:
TableA::whereIn('id',$ids)
->whereNotIn('id', function($q){
$q->select('tabla_id')
->from('tableb');
// more where conditions
})
->get();

Resources