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.
Related
i'd like to ask, how would you write the following query in Laravel Eloquent?
Please note the COALESCE, IF, and the complex LEFT JOIN ... ON (... AND ...).
SELECT COALESCE(IF(customer_group_id=6, prices.price, NULL), products.price) AS finalPrice, prices.customer_group_id, products.*, product_translations.*
FROM `product_categories`
LEFT JOIN `products` ON `product_categories`.`product_id` = `products`.`id`
LEFT JOIN `product_translations` ON `product_translations`.`product_id` = `products`.`id`
LEFT JOIN `prices`
ON (`products`.`id` = `prices`.`product_id` AND `prices`.`customer_group_id` = 6 )
WHERE `product_translations`.`locale` = 'it'
AND `products`.`online` = 1
AND `products`.`sellable` = 1
AND `category_id` = 22
UPDATE: By far, what i came up with is the following:
ProductCategory::leftjoin('products', 'product_categories.product_id', '=', 'products.id')
->leftJoin('product_translations', 'product_translations.product_id', 'products.id')
->leftJoin('prices', function($join) use($customer_group_id) {
$join->on('products.id', '=', 'prices.product_id')
->on('prices.customer_group_id', '=', DB::raw($customer_group_id));
})
->select(
DB::raw('coalesce(if(customer_group_id='.$customer_group_id.',prices.price,NULL), products.price) AS finalPrice'),
'prices.customer_group_id',
'products.*',
'product_translations.*'
)
->where('product_translations.locale', '=', $locale)
->where('products.online', '=', true)
->where('products.sellable', '=', true)
->where('category_id', '=', $this->id);
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();
I have this query that successfully run on mysql workbench:
SELECT
any_value(u.username),
any_value(b.name),
any_value(gc.visit_cycle_id),
any_value(gc.group_number),
any_value(dc.total_customer),
count(*) as total_day
FROM
trackgobackenddb.group_cycles gc
LEFT JOIN (
SELECT
any_value(dc.group_cycle_id) as group_cycle_id,
count(*) as total_customer
FROM
trackgobackenddb.destination_cycles dc
GROUP BY dc.group_cycle_id
) dc ON dc.group_cycle_id = gc.id
LEFT JOIN visit_cycles vc ON gc.visit_cycle_id = vc.id
LEFT JOIN users u ON vc.user_id = u.id
LEFT JOIN branches b ON vc.branch_id = b.id
GROUP BY gc.visit_cycle_id, gc.group_number;
How to convert that query so I can use laravel eloquent or query builder?
You can use DB::select to run complex raw SQL
$sql = "";
$data = DB::select($sql);
Here's my untested attempt using the query builder:
DB::table('group_cycles AS gc')
->leftJoin('destination_cycles AS dc', function ($join) {
$join->on('dc.group_cycle_id', '=', 'gc.id')
->select(['dc.group_cycle_id AS group_cycle_id', DB::raw('select count(*) AS total_customer')]);
})
->leftJoin('visit_cycles AS vc', function ($join) {
$join->on('gc.visit_cycle_id', '=', 'vc.id');
})
->leftJoin('users AS u', function ($join) {
$join->on('vc.user_id', '=', 'u.id');
})
->leftJoin('branches AS b', function ($join) {
$join->on('vc.branch_id', '=', 'b.id');
})
->groupBy('gc.visit_cycle_id', 'gc.group_number')
->get();
I have the following MySQL query:
SELECT
*
FROM
news_posts
WHERE
user_id = ?
AND id NOT IN (SELECT
post_id
FROM
user_read
WHERE
user_id = ?)
I want to make it more "eloquent". I've tried the following, but its (obviously) not working:
NewsPost::where('user_id', Auth::id())
->whereNotIn(function ($query) {
$query->DB::table('user_read')
->select('post_id')
->where('user_id', Auth::id());
})->get();
I'm assuming the 'where' method is executing a simple SQL query on 'new_posts' table. Can you try to rewrite this query and let mysql do the filtering for new posts? (search for LEFT OUTER JOIN on mysql)
SELECT *
FROM news_posts a
JOIN user_read b
ON a.id = b.post_id
WHERE a.user_id = ?
AND b.post_id IS NULL;
Thanks for all the replies! Got it working with the following tweaks:
NewsPost::where('user_id', Auth::id())
->whereNotIn('id', function ($query) {
$query->select('post_id')
->from('user_read')
->where('user_id', Auth::id());
})
->get();
I am trying to make the following query in laravel:
SELECT a.name AS subname, a.area_id, b.name, u. id, u.lawyer_id,u.active_search,
FROM subarea a
LEFT JOIN user_subarea u ON u.subarea_id = a.id
AND u.user_id = ?
LEFT JOIN branch b ON a.area_id = b.id
The idea is to obtain the subareas and see if the search is activated by the user.
The user_subarea table might have a record that matches the id of the subarea table where the active_search is equal to 0 or 1. If it doesn't exist I would like the query to return null.
While I was able to achieve this in raw SQL when I try the same with eloquent in Laravel I am not returning any value. I have done the following:
$query = DB::table('subarea')
->join('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Any help will be much appreciated.
I found by myself the answer it was just to add a lefjoin in the first join. It is not in the laravel docs but works too.
$query = DB::table('subarea')
->lefjoin('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Try this one, If you get a problem, please comment.
$value = \Auth::user()->id;
$query = DB::table('subarea')
->where('user_subarea.user_id', '=',$value)
->leftJoin('user_subarea', 'subarea.id', '=', 'user_subarea.subarea_id')
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('subarea.name AS subname','subarea.area_id', 'branch.name', 'user_subarea.id','user_subarea.lawyer_id','user_subarea.active_search')
->get();