I'm struggling with implementing SQL query into my php code.
The query:
select template_id, min(created_at) as created_at from (
select distinct
root_template_id as template_id,
date_created as created_at,
response_id as response_id
from db.score
inner join db.users ON db.score.supplier_id = db.users.old_id
inner join db.acc ON db.acc.user_id = db.users.id
where db.acc.account_id = 25) as T
group by template_id
I was able to prepare only this part:
$query = DB::table('score')
->selectRaw('DISTINCT root_template_id as template_id, date_created as created_at, response_id')
->join('users', 'score.supplier_id', '=', 'users.old_id')
->join('acc', 'acc.user_id', '=', 'users.id')
->whereIn('acc.account_id', $request->id)
And it works, but it is only responsible for the nested part, for the subquery if I can call it like this. Can someone share any thoughts?
DB::table() usually receive table name as a string, but it can also receive Closure or an Illuminate\Database\Query\Builder instance, so this should do the trick for Laravel's select from subquery:
DB::table(function ($query) use ($request) {
$query->selectRaw('DISTINCT root_template_id as template_id, date_created as created_at, response_id')
->from('score')
->join('users', 'score.supplier_id', '=', 'users.old_id')
->join('acc', 'acc.user_id', '=', 'users.id')
->whereIn('acc.account_id', $request->id)
}, 'T')
->select([
'template_id',
DB::raw("MIN(created_at) AS created_at"),
])
->groupBy('template_id')
->get();
Related
I am new to Laravel,
can anyone help me with this how should I get unique records through this query in laravel query builder?
as of now, I'm getting duplicate records for example red, pink, red, pink, green
here is my query
MySQL query:
select count(*) as aggregate from (select `product`.`id`, `name`, `category`.`category`, group_concat(product_synonyms.product_synonym)as product_synonym, group_concat(product_tags.product_tag) as product_tag from `product` left join `product_tags` on `product`.`id` = `product_tags`.`product_id` left join `category` on `category`.`id` = `product`.`category_id` left join `product_synonyms` on `product`.`id` = `product_synonyms`.`product_id` where `user_id` = 1 and `product`.`deleted_at` is null group by `product_tags`.`product_id`) as `aggregate_table`;
Query builder:
Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym'),DB::raw('group_concat(product_tags.product_tag)) as product_tag')
->groupBy('product_tags.product_id')
->orderBy('product.name', 'ASC')
->paginate(10);
I tried with different join and did many changes, seem I missing something and I couldn't figure it out, and
ending with expecting something from a helping hand
For get only one result in your query you need use:
$productDetails = Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym')**->first();**
for example.
Paginate if you need more result of query. If you need more than one result use ->get()
You can try this
Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym'),DB::raw('group_concat(product_tags.product_tag)) as product_tag')
->distinct()
->groupBy('product_tags.product_id')
->orderBy('product.name', 'ASC')
->paginate(10);
I am using Laravel Framework 6.16.0.
I have the following sql query:
SELECT DISTINCT
`companies`.*
FROM
`companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
`trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
companies.symbol
FROM
`companies`
LEFT JOIN articles a ON a.companies_id = companies.id
WHERE
a.created_at >= 2020-11-12
ORDER BY
created_at
DESC)
ORDER BY
transaction_date
DESC
I have created the following eloquent query:
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
->orderBy('transaction_date', 'desc')
->distinct()
->get('symbol');
However, I am not sure how to pack the in my eloquent query to get all the symbol back that should be excluded.
I highly appreciate your replies!
You should try something like this:
$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', $date)
->whereNotIn('companies.symbol', function ($q) use ($date) => {
$q->select('companies.symbol')
->from('companies')
->leftJoin('articles', 'articles.companies_id', 'companies.id')
->where('articles.created_at', '>', $date)
->distinct()
->get()
})
->orderBy('transaction_date', 'desc')
->distinct()
->get();
It will provide a similar query as you mentioned.
Reference from here.
Also, you can read how to write sub Query from Laravel docs.
Check this one more good answer for that what you need.
I use to PHP and Laravel Framework on my project.
Above code works perfectly
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations','reservations.user_id','=','users.id')
->groupBy('reservations.user_id');
Now Counting all reservation.confirmation column but I want to count only reservation.confirmation column values 1
How I can edit
\DB::raw('count(reservations.confirmation) as confirmation'),
this code
Have you tried see in https://laravel.com/docs/5.6/queries#joins in the section "Advanced Join Clauses", you can add condition in Join function
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations', function ($join) {
$join->on('reservations.user_id', '=', 'users.id')
->where('reservations.confirmation', '=', 1);
})->groupBy('reservations.user_id');
If you want have all sum dolar not depends with confirmation,
you can use 'case' statement:
\DB::raw('sum(case when reservations.confirmation=1 then 1 else 0 end) as confirmation')
or subquery:
\DB::raw('(Select count(*) FROM reservations WHERE user_id = users.id AND confirmation=1) as confirmation')
I have a working query goes like this
SELECT s.name as status, q.name as quality, p.name process, count(*)
FROM plates
JOIN equipment_status_codes s on equipment_status_code_id = s.id
JOIN plate_qualities q on plate_quality_id = q.id
JOIN processes p on process_id = p.id WHERE project_id in
(SELECT id
from projects
WHERE name like 'SPIRIT')
GROUP BY s.name, q.name, p.name ASC with ROLLUP
This works just and returns results just fine.
Now I am trying to put this in laravel syntax, but having some difficulties.
So I was thinking something along these lines.
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'plates.process_id', '=', 'processes.id')
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
...
...
->get();
Would someone help out. Thanks in advance!
Update:
#Govind Samrow
I have tried this query. It works (with couple of small adjustment) But I am not getting the same results as the one I get when I run the sql query.
I included screen shots.
So when I run the sql query.
I get the following results.
When I run the laravel query.
return DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select(DB::raw('equipment_status_codes.name as Status'), DB::raw('IFNULL(plate_qualities.name, NULL) as Quality'), DB::raw('IFNULL(processes.name, NULL) as process'), DB::raw("COUNT(*) as Total" ))
->groupBy(DB::raw('equipment_status_codes.name WITH ROLLUP', 'plate_qualities.name WITH ROLLUP', 'processes.name WITH ROLLUP', 'asc'))
->get();
I get the following.
Almost there, but I am not sure what's going on?! Any ideas?
Try following Query for Joining with where Condition
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', function($join)
{
$join->on('plates.process_id', '=', 'processes.id')
->whereIn('project_id', DB::table('projects')->where('name','LIKE','SPIRIT')->select('id')->get()->toArray());
})
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
->get();
Hope this will help.
Use whereRaw for sub query in where clause Try this:
DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select('equipment_status_codes.name as status', 'plate_qualities.name as quality', 'q.name as quality', 'processes.name as Process', DB::raw("COUNT(*) as Total"))
->groupBy(DB::raw('equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP'))->get();
Here is raw sql result of above that got with toSql():
select `equipment_status_codes`.`name` as `status`, `plate_qualities`.`name` as `quality`, `q`.`name` as `quality`,
`processes`.`name` as `Process`, COUNT(*) as Total from `plates`
inner join `equipment_status_codes` on `equipment_status_code_id` = `equipment_status_codes`.`id`
inner join `plate_qualities` on `plate_quality_id` = `plate_qualities`.`id`
inner join `processes` on `process_id` = `processes`.`id`
where project_id IN(SELECT id from projects WHERE name like 'SPIRIT')
group by equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP
Note: You can use SQL output with $query->toSql() and then compare with your actual SQL query.
You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:
Check its link and get knowladge for laravel query builder:-
https://laravel.com/docs/5.4/queries
I'm trying to write this query in Laravel query
SELECT
table1.*, table2.*
FROM
table1
LEFT JOIN
table2
ON
(table1.id = table2.id AND (table2.field = '' OR table2.field >= '0'))
WHERE
table.id = id
I have problem with how to add inner part AND ( ... ) to the query? Here is what I have so far
$query = Table::select(
DB::Raw('table1.*, table2.*'))
->leftJoin('table2', function($join) {
$join->on('table1.id', '=', 'table2.id')
->where('table2.field', '=', '')
->orwhere('table2.field', '=', '50');
})->where('table1.id', BaseController::getCurrentUser()->id)
->get();
I miss where and how to add AND ...
Do you need to have the AND part as part of ON? If you move it to the WHERE part of your query you could use something like:
$query = Table::select('table1.*', 'table2.*')
->leftJoin('table2', 'table1.id', '=', 'table2.id')
->where('table1.id', BaseController::getCurrentUser()->id)
->where(function ($query){
$query->where('table2.field', '')
->orWhere('table2.field', 50)
});
The result should be the same as from your original query.