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])
;
})
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'm very new to Laravel, how can I make this query in Laravel using Eloquent model:
SELECT
(
SELECT departments.deptname FROM school.counts
LEFT JOIN reference.departments
ON counts.departmentcode = department.departmentcode
WHERE counts.countid = a.countsid
) AS departmentDesc
FROM school.subjecthdr a
LEFT JOIN school.subjectdtls b
ON a.subjectid = b.subjectid;
I don't wish to use raw queries, is there any way? I still appreciate raw query suggestions if there's any.
I think you still need some raw queries.
$dept_desc = \DB::table('school.counts')
->leftjoin('reference.departments', 'counts.departmentcode', '=', 'departments.departmentcode')
->whereRaw('counts.countid = a.countsid')
->selectRaw('departments.deptname');
\DB::table('school.subjecthdr AS a')
->leftjoin('subjectdtls AS b', 'a.subjectid', '=', 'b.subjectid')
->selectRaw('(' . $dept_desc->toSql() . ') AS departmentDesc')
->get();
PS: I think you leftjoin subjectdtls b but it seems you don't need it.
And you are using not only one database, if you want to use Eloquent\Builder,
you need to do something like this:
How to use multiple databases in Laravel
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();
I am trying to join 2 tables on Laravel 5 and have to use Query Builder. I have already got the sql for it but i am not able to convert it to Query Builder syntax. SQL is below
SELECT v.id, r.full_name, b.full_name, s.full_name
FROM vehicles v
LEFT JOIN clients r ON v.representive_client_id = r.id
LEFT JOIN clients b ON v.buyer_client_id = b.id
LEFT JOIN clients s ON v.seller_client_id = s.id
and what i tried is
$query_result = DB::table('vehicles')
->selectRaw($query)
->leftJoin('clients', 'vehicles.representive_client_id', '=', 'clients.id')
->leftJoin('clients', 'vehicles.buyer_client_id ', '=', 'clients.id')
->leftJoin('clients', 'vehicles.seller_client_id ', '=', 'clients.id')
->paginate(30);
The problem is i dont know how to use AS caluse for Query Builder as i need to retrive 3 different types of full_name columns from vehicles table.Anybody can help me about how to write it in a proper Query Builder syntax ?. Any help would be appreciated.
You can use aliases with select columns and tables as well as joins, because the Query Builder will know to quote them correctly. So you can do this without any problems:
$query_result = DB::table('vehicles v')
->select('v.id', 'r.full_name as r_name', 'b.full_name as b_name', 's.full_name as s_name')
->leftJoin('clients r', 'vehicles.representive_client_id', '=', 'r.id')
->leftJoin('clients b', 'vehicles.buyer_client_id ', '=', 'b.id')
->leftJoin('clients s', 'vehicles.seller_client_id ', '=', 's.id')
->paginate(30);
Of course, you can use whatever aliases you want for the selected columns. Actually one of the examples in the Query Builder Selects Documentation uses aliases: email as user_email.
To check the SQL query generated by the Query Builder you can use the toSql method. So in your case instead of ->paginate(30) you can have ->toSql(), which will return a string with the SQL generated by the Query Builder, which you can compare to your raw query and see if it matches.
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'
]);