Join and SUM in Laravel ELoquent - mysql

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

Related

Laravel - Mysql get elements from join table

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

Join tables in Laravel Eloquent

I have three tables like this:
user
id | name | department_id
user_verify
id | code | user_id | department_id
department
id | name
I want to query on table user_verify and join with other tables to get username and department name.
I tried this in my model:
class ListUserVerify extends Model
{
protected $table = 'user_verify';
public function getUserVerify()
{
return $this->select("{$this->table}.code",'user.fullname','department.name')
->join('user', 'user.id', '=', "{$this->table}.user_id")
->join('department', 'department.id', '=', "{$this->table}.department_id")
->get();
}
}
But this function return null, I don't know what's wrong with my query.
Can you show me what's wrong I did?
Thank you very much!
Try it.
return \DB::table("{$this->table}")->select("{$this->table}.code",'user.fullname','department.name')
->join('user', 'user.id', '=', "{$this->table}.user_id")
->join('department', 'department.id', '=', "{$this->table}.department_id")
->get();
Try this
return DB::table('user_verify')->leftjoin('user','user.id','=','user_verify.user_id')
->leftjoin('department','department.id','=','user_verify.department_id')
->select('user.name as username','department.name as departmentname')
->get();

Convert Raw SQL query to Laravel DB Query

I have the following raw SQL query:
select a.id user_id, a.email_address, a.name_first, a.name_last, count(b.id) number_of_videos, sum(b.vimeo_duration) total_duration, sum(b.count_watched) total_playbacks
from users a,
videos b
where a.id = b.tutor_id
and a.email_address in ('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za')
group by a.id;
This correctly gets 6 rows from the database. I'm trying to convert this to a Laravel database query like so:
$totals = DB::table('users')
->select(DB::Raw('users.id as user_id'), 'users.email_address', 'users.name_first', 'users.name_last', DB::Raw('count(videos.id) as number_of_videos'), DB::Raw('sum(videos.vimeo_duration) as total_duration'), DB::Raw('sum(videos.count_watched) as total_playbacks'))
->join('videos', 'users.id', '=', 'videos.tutor_id')
->where('users.id', 'videos.tutor_id')
->whereIn('users.email_address', array('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za'))
->groupBy('users.id')
->get();
This however return 0 rows. Is there anything I'm missing?
It should be smth like below even tho groupBy user id does not help much as id is unique.
$aggregates = [
DB::raw('count(b.id) as number_of_videos'),
DB::raw('sum(b.vimeo_duration) as total_duration'),
DB::raw('sum(b.count_watched) as total_playbacks'),
];
$simpleSelects = ['users.email_address', users.id, 'users.name_first', 'users.name_last'];
$emails = ['candace_rennie#yahoo.com', 'tjm#hiltoncollege.com'....]
$users = Users::select(array_merge($simpleSelects, $aggregates))
->leftJoin('videos as b', function ($join) use ($emails) {
$join->on('b.tutor_id', 'a.id')
->whereIn('users.email_address', $emails);
})
->groupBy('users.id')
->get();
Try to remove this line:
->where('users.id', 'videos.tutor_id')
List item
after sql code convert into laravel
DB::select('posts.id','posts.title','posts.body')
->from('posts')
->where('posts.author_id', '=', 1)
->orderBy('posts.published_at', 'DESC')
->limit(10)
->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();

Dynamic table name in join query alias in Laravel 5

How to alias a table name in Laravel 5?
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin($res_tbl_name, 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
Actually i need the table name alias like below.
$res_tbl_name AS r
Thanks.
Try as given below:
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin("$res_tbl_name as r", 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
And then use 'r' wherever you used $res_tbl_name