I am using LARAVEL 4 with MySQL back-end. I am novice to it.
I have a statement that returns records from 3 different tables as below :
$templates = Template::with('children')
->leftJoin('template_masters', function($join) {
$join->on('templates.template_master_id', '=', 'template_masters.id');
})
->leftJoin('surveyes', function($join) {
$join->on('templates.survey_id', '=', 'surveyes.id');
})
->get([
'templates.id',
'templates.survey_id',
'surveyes.title', // Here I want the IFNULL() condition e.g. IFNULL('surveyes.title','templates.title')
'templates.type',
'templates.created_at',
'template_masters.is_default'
]);
Basically this creates a query something like :
select `templates`.`id`,
`templates`.`survey_id`,
`surveyes`.`title`,
`templates`.`type`,
`templates`.`created_at`,
`template_masters`.`is_default`
from `templates`
left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id`
left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
But I want this query like :
select `templates`.`id`,
`templates`.`survey_id`,
IFNULL(`surveyes`.`title`, `templates`.`title`),
`templates`.`type`,
`templates`.`created_at`,
`template_masters`.`is_default`
from `templates`
left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id`
left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
In short, instead of surveyes.title, I want IFNULL(surveyes.title,templates.title).
How can I achieve this in ->GET([]) statement of given Eloquent ORM?
Thanks.
You need to use raw statement:
...
->get([
'templates.id',
'templates.survey_id',
DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),
// or if you use namespace:
\DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),
'templates.type',
'templates.created_at',
'template_masters.is_default'
]);
Related
i have this query to return data from two tables based on DISTINCT destination_tbls.destination
like the following:
SELECT DISTINCT
destination_tbls.destination,
MIN(sms_details.id),
MIN(sms_details.msg_timestamp) AS TIMESTAMP,
MIN(destination_tbls.count)
FROM
sms_details
JOIN
(
SELECT
*
FROM
destination_tbls
)
destination_tbls
ON destination_tbls.id = sms_details.destination_tbls_id
GROUP BY
destination_tbls.destination;
Now how to use the paginate with them,
I tried something like this but don't work:
DB::select('
SELECT DISTINCT destination_tbls.destination,MIN(sms_details.id),MIN(sms_details.msg_timestamp) AS TIMESTAMP,MIN(destination_tbls.count)
FROM sms_details
JOIN(SELECT * FROM destination_tbls) destination_tbls ON destination_tbls.id=sms_details.destination_tbls_id
GROUP BY destination_tbls.destination
')->simplePaginate(100);
Any help would be appreciated!
If you want to use laravel's pagination, you need to write the query using the query builder methods.
$results = DB::table('sms_details')
->select('destination_tbls.destination')
->selectRaw('min(sms_details.id)')
->selectRaw('min(sms_details.msg_timestamp) as timestamp')
->selectRaw('min(destination_tbls.count)')
->distinct()
->joinSub(
function ($sub) {
$sub->from('destination_tbls');
},
'destination_tbls',
function ($join) {
$join->on('destination_tbls.id', '=', 'sms_details.destination_tbls_id');
}
)
->groupBy('destination_tbls.destination')
->simplePaginate(100);
Since you're not really doing anything in the subquery join, you could join the table instead.
$query = DB::table('sms_details')
->select('destination_tbls.destination')
->selectRaw('min(sms_details.id)')
->selectRaw('min(sms_details.msg_timestamp) as timestamp')
->selectRaw('min(destination_tbls.count)')
->distinct()
->join('destination_tbls', 'destination_tbls.id', '=', 'sms_details.destination_tbls_id')
->groupBy('destination_tbls.destination')
->simplePaginate(100);
I am using laravel 8. I have this mysql command which I want to convert into laravel query builder style:
select allocation.*, leav_leave_types.leave_type_code
from (
select * from leav_employee_annual_leave_allocations
where leave_year_id = $year_id and employee_id = $user_id
) as allocation
left join leav_leave_types on (leav_leave_types.id = allocation.leave_type_id)
Actually I want to apply a where clause first and then perform a left join for better performance.
How can I convert it into query builder style?
The only thing from your query that is not currently in the documentation is using a subquery as the main table.
This can be done by passing either a Closure or a Builder instance to the table() or from() method.
DB::table(closure, alias)
DB::table(builder, alias)
DB::query()->from(closure, alias)
DB::query()->from(builder, alias)
Using a Closure:
DB::table(function ($sub) use ($user_id, $year_id) {
$sub->from('leav_employee_annual_leave_allocations')
->where('leave_year', $year_id)
->where('employee_id', $user_id);
}, 'allocation')
->select('allocation.*', 'leav_leave_types.leave_type_code')
->leftJoin('leav_leave_types', 'leav_leave_types.id', 'allocation.leave_type_id')
->get();
DB::query()
->select('allocation.*', 'leav_leave_types.leave_type_code')
->from(function ($sub) use ($user_id, $year_id) {
$sub->from('leav_employee_annual_leave_allocations')
->where('leave_year', $year_id)
->where('employee_id', $user_id);
}, 'allocation')
->leftJoin('leav_leave_types', 'leav_leave_types.id', 'allocation.leave_type_id')
->get();
Using a Builder instance
$sub = DB::table('leav_employee_annual_leave_allocations') // or DB::query()->from('leav_employee_annual_leave_allocations')
->where('leave_year', $year_id)
->where('employee_id', $user_id);
DB::table($sub, 'allocation')
->select('allocation.*', 'leav_leave_types.leave_type_code')
->leftJoin('leav_leave_types', 'leav_leave_types.id', 'allocation.leave_type_id')
->get();
// personally my favorite way. I find it very readable.
$sub = DB::table('leav_employee_annual_leave_allocations') // or DB::query()->from('leav_employee_annual_leave_allocations')
->where('leave_year', $year_id)
->where('employee_id', $user_id);
DB::query()
->select('allocation.*', 'leav_leave_types.leave_type_code')
->from($sub, 'allocation')
->leftJoin('leav_leave_types', 'leav_leave_types.id', 'allocation.leave_type_id')
->get();
The generated SQL looks like this
select "allocation".*, "leav_leave_types"."leave_type_code" from (
select * from "leav_employee_annual_leave_allocations"
where "leave_year" = ? and "employee_id" = ?
) as "allocation"
left join "leav_leave_types" on "leav_leave_types"."id" = "allocation"."leave_type_id"
If you want a parenthesis around your join condition to be generated, you should use one of the following notations instead.
leftJoin('leav_leave_types', ['leav_leave_types.id' => 'allocation.leave_type_id'])
leftJoin('leav_leave_types', function ($join) {
$join->on(['leav_leave_types.id' => 'allocation.leave_type_id']);
})
leftJoin('leav_leave_types', function ($join) {
// will generate a parenthesis if there's more than one condition
$join->on('leav_leave_types.id', 'allocation.leave_type_id')
->on(...) // and condition
->orOn(...); // or condition
})
Alternatively, you could turn the SQL around to
select *,
( SELECT leave_type_code
FROM leav_leave_types
WHERE id = allocation.leave_type_id
) AS leave_type_code
FROM leav_employee_annual_leave_allocations AS allocation
where leave_year_id = $year_id and employee_id = $user_id
(This might be more efficient.)
In either case leav_employee_annual_leave_allocations would benefit from INDEX(employee_id, leave_year_id).
I'm currently trying to use the Eloquent query builder to create a join with multiple clauses, one of which being an IN clause.
The type of query I would like to create would be
SELECT * FROM trusts t
LEFT JOIN trust_group tg ON tg.trust_id = t.id
AND tg.group_id IN (1,2,4)
I've tried
->leftJoin('trust_group', function($join) {
$join->on('trust_group.trust_id', '=', 'trusts.id');
$join->on('trust_group.group_id', 'IN', [1,2,4]);
})
which results in
and `trust_group`.`group_id` = `IN`
and I've also tried
->leftJoin('trust_group', function($join) {
$join->on('trust_group.trust_id', '=', 'trusts.id');
$join->on(DB::raw('trust_group.group_id IN (1,2,4)'));
})
but this results in a query containing something along the lines of
and trust_group.group_id IN (1,2,4) = ``
(Obviously those group IDs are for example purposes, and would by dynamic)
Can Eloquent support IN clauses on joins?
This is only part of a pretty large query, so would prefer to use the join rather than use a whereIn
As this is kinda deadlock at the moment, I am posting this as an answer until this is officially PRed. Unfortunately joining with an In clause is not yet supported officially. There are some discussions in this closed thread
You can use it as raw query :
<?php
$results = DB::select("
SELECT * FROM trusts t
LEFT JOIN trust_group tg ON tg.trust_id = t.id
AND tg.group_id IN (?)", $groupIds);
Also there is Model::hydrate($array) method if you want to have eloquent collection back from result array.
This is a pretty old post, but for anyone searching, you can now simply use where functions to build more complex joins (tested in Laravel 7) :
->leftJoin('trust_group', function($join) {
$join
->on('trust_group.trust_id', '=', 'trusts.id')
->whereIn('trust_group.group_id', [1, 2, 4])
;
})
I have two table customer_id namely tbl_customer and tbl_stocks connected on the same database. My logic about this problem is JOIN sql statement.
This is for Laravel and MySQL, so far i've tried this on PHP and is working fine but when I implement it on laravel it is not working i wonder why?
here is my code in PHP and want to convert it to laravel but I dont know where to put? will i put it in the View or in the Controller
$query = "SELECT c.*, s.* FROM tbl_customer c JOIN tbl_stock s ON s.customer_id = c.customer_id AND c.customer_id = 1";
Controller
$data = DB::table('tbl_customer')
->join ...... //Im not sure about this
->select .... // neither this
->get();
print_r($data)
Model
I have no codes on my model
Routes
Route::get('/admin/shopcontrol', 'Admin\ShopsController#testquery');
I expect a result of fetching or getting the query or result of the values in just a simple echo and the fetch join is connected
Have you checked the Laravel site?
https://laravel.com/docs/5.7/queries#joins
It has a demonstration you could use to reorganize your code.
As it follows below from the site.
Joins
Inner Join Clause
The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:
$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();
You may find more information there if it suits you.
Try this:
$data = DB::table('tbl_customer')
->join('tbl_stock', 'customer_id', '=', 'tbl_customer.customer_id')
->select('tbl_customer.*', 'tbl_stock.*')
->where('customer_id', '=', 1)
->get();
Can I write something like this:
$post = Post::join(['author'])->find($postId);
$authorName = $post->author->name;
To produce only ONE select with inner join (no 2 selects) and without using DB query builder
SELECT
post.*,
author.*
FROM post
INNER JOIN author
ON author.id = post.author_id
WHERE post.id = ?
You can do it in Eloquent using the join method:
$post = Post::join('author', function($join)
{
$join->on('author.id', '=', 'post.author_id');
})
->where('post.id', '=', $postId)
->select('post.*', 'author.*')
->first();
Please note that your results in $post will be an object where their attributes will correspond to the result set, if two columns has the same name it will be merged. This happen when using:
->select('post.*', 'author.*')
To avoid this, you should create alias to those columns in the select clause as shown below:
->select('post.id AS post_id', 'author.id AS author_id')
Try
Post::join('author',function($join){
$join->on('author.id','=','post.author_id');
})->where('post.id','=',$postId)->select('post.*','author.*');