Laravel 5.4 Error when Joining two tables - mysql

I need to join two tables in laravel model. Here is my query,
$id="1002";
$resultsInCalls = DB::table('qlog')
->select('user_master.fname','user_master.lname','qlog.data2')
->whereDate('created', '=', date('Y-m-d')) // this day
->join('qlog', 'qlog.agent', '=', 'user_master.sip_id')
->where('agent', '=', $id)
->where(function ($query) {
$query->where('event', '=', 'COMPLETEAGENT')
->orWhere('event', '=', 'COMPLETECALLER');
})
->take(5)
->get();
But I run this query I get following error.
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'qlog' (SQL: select `user_master`.`fname`, `user_master`.`lname`, `qlog`.`data2` from `qlog` inner join `qlog` on `qlog`.`agent` = `user_master`.`sip_id` where date(`created`) = 2017-11-29 and `agent` = 1002 and (`event` = COMPLETEAGENT or `event` = COMPLETECALLER) limit 5)
I read related questions. But I can't figure it out. How to fix this error.

Here I get it done,
$resultsInCalls = DB::table('qlog')
->join('user_master as user_table', 'qlog.agent', '=', 'user_table.sip_id')
->select('user_table.fname','user_table.lname','qlog.data2')
->whereDate('created', '=', date('Y-m-d')) // this day
->where('agent', '=', $id)
->where(function ($query) {
$query->where('event', '=', 'COMPLETEAGENT')
->orWhere('event', '=', 'COMPLETECALLER');
})
->take(5)
->get();

Related

Joining same table twice in Laravel

I'm building an application on Laravel where I need to join the same table with some condition
I'm having a project_associate_brand table which includes following columns:
project_id | brand_id | product_group_id | product_sub_group_id
I need to fetch out brands associated with project with respect to product_group_id and product_sub_group_id and also which are the other brands associated with them
To execute this I tried:
AssociatedBrands::where('project_associate_brand.brand_id', '=', $id)
->leftjoin('project_associate_brand as pr_brand', function ($join) {
$join->on('project_associate_brand.project_id', '=', 'pr_brand.project_id')
->where('project_associate_brand.product_group_id', '=', 'pr_brand.product_group_id')
->where('project_associate_brand.product_subgroup_id', '=', 'pr_brand.product_subgroup_id');
})
->leftjoin('brands as b', function ($join) {
$join->on('pr_brand.brand_id', '=', 'b.id')->whereNotIn('pr_brand.brand_id', [$id]);
})
->select('project_associate_brand.*', 'b.id as other_brand_id', 'b.title as other_brand_title')
->paginate(15);
I'm not getting the desired results, I tried removing few of the where clause, when I remove product_group_id and product_sub_group_id contraints I was able to get results
AssociatedBrands::where('project_associate_brand.brand_id', '=', $id)
->leftjoin('project_associate_brand as pr_brand', function ($join) {
$join->on('project_associate_brand.project_id', '=', 'pr_brand.project_id');
//Removed other where clause
})
->leftjoin('brands as b', function ($join) {
$join->on('pr_brand.brand_id', '=', 'b.id')->whereNotIn('pr_brand.brand_id', [$id]);
})
->select('project_associate_brand.*', 'b.id as other_brand_id', 'b.title as other_brand_title')
->paginate(15);
Any better approach is welcome. Further I would like to execute with() eager loading of relations

how to use MIN and MAX sql query in Laravel Eloquent

i want to use min and max laravel elaquent at the same line, is that posible?
Appointmentsetting::where('Day','=',1)
->whereIn('PersonID', function ($query) {
$query->select('p.id')
->from('users as p')
->join('appointmentsettings as aps', 'aps.PersonID', '=', 'p.id')
->where('p.active', '=', 1)
->where('aps.CompanyID', '=', 1)
->orWhereIn('aps.PersonID', function ($query2) {
$query2->select('cps.user_id')
->from('companypersonstructs as cps')
->where('cps.CompanyID', '=', 1);
})
->groupBy('aps.PersonID');
})
->where('active', '=', 1)
->select(\DB::raw("SELECT MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo"));
->get();
i got error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'SELECT
MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo from
`appointmentsetting' at line 1
->selectRaw(" MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo");
please put above query and try. the main problem in your query is you are using select two time there is no need for write select inside select or selectRaw
for more about raw query click here
Appointmentsetting::where('Day','=',1)
->whereIn('PersonID', function ($query) {
$query->select('p.id')
->from('users as p')
->join('appointmentsettings as aps', 'aps.PersonID', '=', 'p.id')
->where('p.active', '=', 1)
->where('aps.CompanyID', '=', 1)
->orWhereIn('aps.PersonID', function ($query2) {
$query2->select('cps.user_id')
->from('companypersonstructs as cps')
->where('cps.CompanyID', '=', 1);
})
->groupBy('aps.PersonID');
})
->where('active', '=', 1)
->select(\DB::raw("MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo"));
->get();

Laravel count with where on Query Builder with joins

Good day all, I am trying to count all records in a table but only if the table does not contain data in a specific column (deleted_at). It is a join table the table names are companies and employees. I am currently counting the records with a DB::raw but it should only count it if the deleted_at column is null. Please understand that i am a beginner.
public function index()
{
$user = Auth::user()->id;
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('COUNT(e.id) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->where('c.deleted_at', '=', null)
->groupBy('c.id')
->get();
return view('account.companies.index')
->with('companies', $companies);
}
If you are using Mysql then you could use conditional aggregation
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('SUM(c.deleted_at IS NULL) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->groupBy('c.id')
->get();
In mysql when an expression is used inside sum(a= b) it will result as a boolean 0/1 so you can get your conditional count using above
Or you could use whereNull() method in your query
->whereNull('c.deleted_at')
Use this code:
$employeeCount = DB::table('employees')
->select('companies.name', DB::raw('count(employees.id) as employee_count'))
->join('companies', 'employees.company','=','companies.id')
->groupBy('companies.id')
->get();

Where clause on join query laravel 4.2

I have 2 tables 'users' and 'instantUsers'. I want to join them on users.id = instantUsers.user_id and want to add 2 where clauses on the resulting. I'm not getting how to do both. The query I'm using is -
DB::table('users')
->join('instantUsers', function($join) use ($userId) {
$join->on('users.id', '=', 'instantUsers.user_id');
})
->where('instantUsers.instantMode', '=', '1')
->where (function($query) use ($userId) {
$query->where('instantUsers.user_id', '!=', $userId);
})
->get();
You can try this one maybe this will help you:
DB::table('users as table1')->join('instantUsers as table2','table1.id','=','table2.fkId') ->where('table2.instantMode','=','1')->where('table2.user_id','!=',$userId)->get();
Your 'instantUsers.instantMode','=','1' expression can be done in a join, resulting in a better performance.
I would write it like this
DB::table('users')
->join('instantUsers', function($join) use ($userId) {
$join
->on('users.id', '=', 'instantUsers.user_id')
->on('instantUsers.instantMode', '=', 1);
})
->where('users.id', '!=', $userId)
->get();

Laravel Query Builder Nested Join and Alias

How to create this query using Laravel's Query Builder:
SELECT `content`.`tagable_id`,`taged`.`tag_id`
FROM `taged`
RIGHT JOIN
(SELECT `taged`.`tagable_id`,`taged`.`tag_id`
FROM `taged`
WHERE `taged`.`mask_flag`='0'
AND `taged`.`tagable_type`='App\\\Post'
AND `taged`.`user_id`='1') AS `content`
ON `taged`.`mask_flag`='1'
AND `content`.`tagable_id`=`taged`.`tagable_id`
AND `taged`.`tagable_type`='App\\\Post'
AND `taged`.`user_id`='1'
The parenthesis around the inner SELECT taged.tagable_id... is where my main problem lies.
Here is your Laravel query:
$result = DB::table('taged')
->select('content.tagable_id', 'taged.tag_id')
->rightJoin(DB::raw('SELECT tagable_id, tag_id FROM taged AS content'), function($join)
{
$join->on('taged.mask_flag', '=', 1);
$join->on('content.tagable_id', '=', 'taged.tagable_id');
$join->on('taged.tagable_type', '=', 'App\\\Post');
$join->on('taged.user_id', '=', 1);
})
->where('content.mask_flag', '=', 0);
->where('content.tagable_type', '=', 'App\\\Post');
->where('content.user_id', '=', 1);
->get();