how to write sql query to laravel - php

i have a sql query like this and i want to convert it to laravel how i can do it?
i have try it, but i confusing on wherein and join
sql query
SELECT MIN(StartFrom) as StartFrom,MAX(EndTo) as EndTo from appointmentsettings
WHERE day=1
and PersonID IN (
SELECT p.id
FROM users p
JOIN appointmentsettings aps ON p.id = aps.PersonID
WHERE p.active=1 AND aps.CompanyID = 1 OR aps.PersonID IN(
SELECT cps.user_id
from companypersonstructs cps
WHERE cps.CompanyID =1
) group by aps.PersonID
)
and active=1
here what i try
Appointmentsetting::select('StartFrom', 'EndTo')
->min('StartFrom')
->max('EndTo')
->where(['Day'=>$day, 'Active'=>1])
->whereIn('PersonID', function ($query) use ($id) {
$query->select('p.id')
->from('users as p')
$query->join('appointmentsettings as aps', 'p.id', '=', '')
->where(["user_id" => $id, 'Active' => 1])->get();
})->orderBy('id')->get();

Appointmentsetting::select('StartFrom', 'EndTo')
->min('StartFrom')
->max('EndTo')
->where(['Day'=>$day, 'Active'=>1])
->whereIn('PersonID', function ($query) use ($id) {
$query->select('p.id')
->from('users as p')
->join('appointmentsettings as aps', 'p.id', '=', '')
->where(["user_id" => $id, 'Active' => 1]);
})->orderBy('id')->get();
You have an error in your join inside the function. Try the above code.
Also you must use get() only at the end of the query and not inside the function itself.

DB Query way
DB::table('appointmentsettings')->join('users','p.id','=','')
->select(DB::raw('MIN(StartFrom) as StartFrom','Max(EndTo) as EndTo'))
->where([['user_id',$id],['Active','1']])
->groupBy('appointmentsettings.PersonID)
->orderBy('id','ASC')
->get();

Related

How to effectively using laravel 5.5 eloquent on complex join and group

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

Laravel 5.2 - Left Join DB::Raw not working?

I have the following query where I'm trying to use DB::Raw() for the left join but I'm getting error:
Missing argument 2 for Illuminate\Database\Query\Builder::leftJoin()
This is my query:
return $this->model->from('alerts as a')
->leftJoin(DB::Raw("locations as l on l.id = JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.locationId'))"))
->leftJoin(DB::Raw("industries as i on find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries')))"))
->where('user_id', '=', $userId)
->selectRaw("a.id
, a.name
, a.criteria
, GROUP_CONCAT(DISTINCT(i.name) SEPARATOR ', ') as 'Industries'
->groupBy('a.id')
->orderBy('a.created_at', 'desc');
The leftJoin function is declared like this:
public function leftJoin($table, $first, $operator = null, $second = null)
You want to pass your raw functions in as the second column:
return $this->model->from('alerts as a')
->leftJoin('locations AS l', 'l.id', '=', DB::Raw("JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.locationId'))"))
->leftJoin('industries as i', function($join){
$join->on(DB::raw("find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries')))",DB::raw(''),DB::raw('')));
})
->where('user_id', '=', $userId)
->selectRaw("a.id
, a.name
, a.criteria
, GROUP_CONCAT(DISTINCT(i.name) SEPARATOR ', ') as 'Industries'")
->groupBy('a.id')
->orderBy('a.created_at', 'desc');
The find_in_set suggestion came from here.
I'm not sure what '$.locationId' is, but if it's a variable, you can pass that along as a parameter within an array as the second parameter on the DB::raw() function.

MySQL query to Laravel Eloquent

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

Convert mysql query into Eloquent laravel query

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

Query from two tables laravel with multiple conditions

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.

Categories