Laravel - Mysql get elements from join table - mysql

I am getting the total carOwnerDept(department id) from cars table which has relation with department table
but i can't get the issue from cars table.
Here's the code
$dept = DB::table('department')
->select('department.name', DB::raw('COUNT(cars.carOwnerDept) AS dept_count'))
->join('cars', 'department.id', '=', 'cars.carOwnerDept')
->select('department.name', 'cars.issue')
->groupBy('department.name')
->where('cars.carType', '=', 'Internal Customer')
->whereDate('cars.created_at', '>=', $from)
->whereDate('cars.created_at', '<=', $to)
->get();
Views
<table>
<tr>
<th>Department</th>
<th>Issues</th>
<th>Total</th>
</tr>
#foreach($dept as $depts)
<tr>
<td>{{$depts->name}}</td>
<td>{{$depts->issue}}</td>
<td>{{$depts->dept_count}}</td>
</tr>
#endforeach
</table>
DB Structure
cars
id | carOwnerDept | issue
1 1 barcode problem
2 3 scanner problem
3 2 barcode problem
department
id | name
1 QA
2 PP
3 PE

You may get the number of car owner departments as shown below.
$dept = DB::table('department')
->select(DB::raw('(SELECT COUNT(carOwnerDept) FROM cars WHERE carOwnerDept=department.id) AS dept_count'))
->join('cars', 'department.id', '=', 'cars.carOwnerDept')
->select('department.name', 'cars.issue')
->where('cars.carType', '=', 'Internal Customer')
->whereDate('cars.created_at', '>=', $from)
->whereDate('cars.created_at', '<=', $to)
->get();

I highly recommend that you create functions on your models so that you don't need to input raw queries. Fewer codes and easier to understand.

Try This.
$dept = DB::table('department')
->join('cars', 'department.id', '=', 'cars.carOwnerDept')
->select('department.name', DB::raw('COUNT(cars.carOwnerDept) AS dept_count'), 'cars.issue')
->where('cars.carType', '=', 'Internal Customer')
->whereDate('cars.created_at', '>=', $from)
->whereDate('cars.created_at', '<=', $to)
->groupBy('department.name')
->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 get total users average time passed 7 days

I want to get the per day total users average usage time for passed 7 days i written the the SQL for each users average time it's coming perfectly but i have an u\issues in LARAVEL SQL function please help fix this SQL.
$currentTime = Carbon::today();
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy('acu_name')
->get();
You need to use GROUP BY for this, e.g.:
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy('acu_name', DB::raw('DATE(acu_at)'))
->get();
update
If you just need daily average for all the users, you can remove acu_name from group by, e.g.:
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy(DB::raw('DATE(acu_at)'))
->get();
Correct Answer is
$userUsage = DB::table('active_user')
->select(DB::raw('DATE(acu_at) as date'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('COUNT(DISTINCT `acu_name`) as users'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy(DB::raw('DATE(acu_at)'))
->orderBy(DB::raw('DATE(acu_at)'))
->get();
foreach($userUsage as $usUa)
{
$avegTime = ($usUa->averageTime/$usUa->users);
echo "['".$usUa->date."',".$avegTime."],";
}

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

Join 3 table with query builder in laravel

I have a 3 table questions,registrations,ssi_tracks i need to get details from the registraions table by corresponding to other two tables
i need to get details from registrations based on
questions.question_schedul=0 ,ssi_tracks.track_first_status
i have wrote query but it says the column is not found here is my query
$register = DB::table('registrations')
->join('questions', 'registrations.registration_id', '=', 'questions.question_id')
->join('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
->select('address', 'model', 'chassis', 'delivery_date','ssi_tracks.track_first_status')
->where([["questions.question_schedul", "=", $dropselected] and ['ssi_tracks.track_first_status',0]])
->get();
Try this:
$register = DB::table('registrations as R')
->select('R.address', 'R.model', 'R.chassis', 'R.delivery_date','S.track_first_status')
->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')
->join('ssi_tracks as S','R.registration_id','=','S.registration_id')
->where('Q.question_schedul', '=', $dropselected)
->where('S.track_first_status', '=', 0)
->get();
Make sure you have used the right column here from question table for matching registration id:
->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')
try this query :
$register = DB::table('registrations')
->leftJoin('questions', 'registrations.registration_id', '=', 'questions.question_id')
->leftJoin('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
->select('registrations.address', 'registrations.model', 'registrations.chassis', 'registrations.delivery_date','ssi_tracks.track_first_status')
->where(['questions.question_schedul'=>$dropselected,'ssi_tracks.track_first_status'=>0])
->get();

Join and SUM in Laravel ELoquent

Database Structure is as follows:
Table: users
id | name | email | password
Table: analytics
id | user_id(fk) | article_id(fk) | revenue | date | clicks
Now I want the list of all users with the sum of their own revenue from these two Tables.
What I tried is as follows:
$users = User::select('users*', 'analytics.*', 'SUM(analytics.revenue)')
->leftJoin('analytics', 'analytics.user_id', '=', 'users.id)
->where('analytics.date', Carbon::today()->toDateString())
->get();
But it is throwing me error.
You may try this
$users = User::select('users*', 'analytics.*', DB::raw('SUM(analytics.revenue) As revenue'))
->leftJoin('analytics', 'analytics.user_id', '=', 'users.id')
->where('analytics.date', Carbon::today()->toDateString())
->get();
$users = User::select(\DB::raw('users.*, SUM(analytics.revenue) as revenue'))
->leftJoin('analytics', 'analytics.user_id', '=', 'users.id')
->groupBy('users.id')
->get();
This maybe a bit late. Maybe will help someone else.
You need to include every select columns in groupBy. In your case:
$users = User::select('users.id', 'users.name', 'users.password', 'analytics.date', 'analytics.clicks', 'SUM(analytics.revenue) as revenue')
->leftJoin('analytics', 'users.id', '=', 'analytics.user_id')
->where('analytics.date', Carbon::today()->toDateString())
->groupBy('users.id', 'users.name', 'users.password', 'analytics.date', 'analytics.clicks')
->get();