get total count in each ids from different table in laravel - php

i want to get each id's total count from another table named assign job. i saved user data into my users table and i add 3 jobs into assign job table with user id.
but now i want to get total added jobs from assign job table where user ids in my users table at once.
I wrote this function
$assignjob = DB::table('users')
->join('assign_jobs', 'users.user_id', '=', 'assign_jobs.user_id')
->get()
->count();
but this shows me total count in my assign job table. but i want to get different count for each user ids.
i want to assign different color rows with this assign job total count values.
can any one help me.
User Table:
|---------------------|------------------|
| user_id | name |
|---------------------|------------------|
| 123 | john |
|---------------------|------------------|
| 234 | peter |
|---------------------|------------------|
assign job table:
|---------------------|------------------|
| id | user_id |
|---------------------|------------------|
| 1 | 123 |
|---------------------|------------------|
| 2 | 123 |
|---------------------|------------------|
| 3 | 234 |
|---------------------|------------------|
| 4 | 234 |
|---------------------|------------------|

You need to use GROUP BY clause for your user's id column and add COUNT() to your select. Try:
DB::table('users')
->select('users.user_id', DB::raw('COUNT(assign_jobs.user_id) AS jobs_count'))
->join('assign_jobs', 'users.user_id', '=', 'assign_jobs.user_id')
->groupBy('users.user_id')
->get();

Select distinct usesr ID to loop into it to have the count for each users

try this:
add below relation to User Model:
public function assignJobs()
{
return $this->hasMany(AssignJob::class, 'user_id', 'user_id');
}
and in controller:
User::withCount('assignJobs')->get();

Related

Getting result from array of Ids in Laravel

I've a following attendance table:
id | grade_id | subject_id | date | students
1 | 2 | 6 | 2020-05-05 | [3,6,8,11,17,21,20,19]
I want to fetch all rows with name of all students from array of Ids.
What I've tried is:
$result[] = Attendance::where('date', '=', $day)
->with('grades', 'subjects')
->join('students', function($join) {
$join->on('students.id', '=', 'attendances.id')
->where('students.id', '=', 'attendances.students');
})->get();
But couldn't get result. Please help me!
It is not a proper table structure.Will be better if you make another table like
id | attendance_id | student_id
1 | 1 | 3
1 | 1 | 6
And make its relation in model with attendance and student table.This way table will be normalized and will be easy to handle relationship.

How can I calculate total price of an invoice?

I have two three tables:
// invoices
+----+----------------+
| id | invoice_code |
+----+----------------+
| 1 | d09823r230r4 |
| 2 | 34tf354f45tf |
+----+----------------+
// commodities
+----+-------------+------------+--------+
| id | invoice_id | product_id | number |
+----+-------------+------------+--------+
| 1 | 1 | 1 | 2 |
| 2 | 1 | 3 | 4 |
+----+-------------+------------+--------+
-- number columns is the number of each ordered product in the invoice
// products
// invoices
+----+-----------+---------+
| id | name | price |
+----+-----------+---------+
| 1 | SFX-300 | 15000 |
| 2 | GB32-b10 | 2000 |
| 3 | SVX-m30 | 1200 |
+----+-----------+---------+
All I need to do is calculating the total price of an invoice. Here is the formula to calculate the total price for invoice x:
$total_invoice_price = 0;
foreach( $invoice_x->commodities as $commodity){
$total_invoice_price += ( $commodity.number * <products.price> )
}
echo $total_invoice_price;
The problem is about getting <products.price>. It needs one more join to products table. Any idea how can I do that using Laravel relationships ?
If you just need the total price, this could be done in pure sql with aggregate statements and joins over the three tables.
SELECT invoice.invoice_code, SUM(product.price * commodities.number)
FROM invoice
JOIN commodities ON invoice.id = commodities.invoice_id
JOIN product ON product.id = commodities.product_id
GROUP BY invoice.id
To save the query, you should do eager loading using "with()" the model you wish to join.
I'm not sure how you named your model and how well it linked to each other.
Let's assume that it've been done in the conventional way.
Here is the script.
$total_invoice_price = $invoice_x->commodities
->with('products')
->get()
->map(function ($commodity) {
return $commodity->number * $commodity->product->price;
})
->sum();
What I've done is after getting the products joined with each commodity. I do the get() to have the commodities collection. The from the collection, we do map on each commodity and return the number and price of product. Then we multiply and return as the sum of each commodity record. After that we sum all the totals to the grand total and get your result.
I wrote the code without testing, so try to adjust it to your code.
Please check below Query
$invoices_total = DB::table('invoices')
->join('products', 'invoices.id', '=', 'commodities.invoice_id')
->join('commodities', 'products.id', '=', 'commodities.product_id')
->sum('products.price * commodities.number')
->groupBy('invoices.id')
->get();

How can I make a relation between tables in Laravel?

I have three tables like these:
// users
+----+-----------+
| id | user_name |
+----+-----------+
| 1 | Jack |
| 2 | Peter |
| 3 | John |
+----+-----------+
// skills
+----+------------+
| id | skill_name |
+----+------------+
| 1 | PHP |
| 2 | HTML |
| 3 | Laravel |
| 4 | MySQL |
| 5 | jQuery |
+----+------------+
// skill_user
+----------+---------+
| skill_id | user_id |
+----------+---------+
| 2 | 1 |
| 5 | 1 |
| 1 | 2 |
| 2 | 2 |
| 4 | 2 |
+----------+---------+
Now I want to get all skills of one specific user. I can do that by using a join clause in a raw sql query:
SELECT s.skill_name
FROM skills s
JOIN skill_user su ON s.id = su.skill_id
WHERE su.user_id = :user_id
/* output (assuming :user_id is 1)
+------------+
| HTML |
| jQuery |
+------------+
Ok All fine. Now I want to know, how can I do that by adding a method in the model of Laravel framework? All I'm trying to do is using belongsTo(), hasOne(), hasMany() etc ..
To do in Eloquent way, you need to add the relationship. In your case, it is many-to-many relationship so in User.php, add this function to declare the relationship:
public function skills() {
$this->belongsToMany(\App\Skill::class, 'skill_user', 'user_id', 'skill_id');
}
Then,
Access it like this to eager load it:
$users = \App\User::with('skills')->get();
OR
Say you have a single user,
$user = User::where('id', 1)->first(); // Get the user with id = 1
and to get the skill for that user:
$user->skills;
OR
If you don't want to do using Eloquent way, you can use Query Builder. Note that, using this method, you basically join it manually so you don;t need to add any method to the Model:
\DB::table('users')
->join('skill_user', 'skill_user.user_id','=', 'users.id')
->join('skills', 'skill_user.skill_id', '=', 'skills.id')
->select('*')
->where('users.id', 1)
->get();
You have to use belongsToMany relationships. Assuming you will create SkillUser model for skill_user table. Add the following code to User Model
public function skills() {
$this->belongsToMany('App\SkillUser', 'skill_user', 'user_id', 'skill_id');
}
Now you can access it by
$users->skills();
I assume you are talking about Many to Many relationship between Users and skills, then the example given in Laravel many-to-many speaks about it.

Join 2 tables together and get return all data where it matches (PHP/Laravel5.2 using MySQL)

I have a variable called $category which a user selects. On submit I need to look inside a table (profiles) for where the $category matches and pull back all of those profiles then look into the likes table and return all matching records for the returned profiles.
My database looks like:
TABLE: profiles
ID | username | category
-------------------------
1 | x | band
2 | y | airline
3 | z | airline
TABLE: likes
ID | account_id | likes | created_at
---------------------------------------
1 | 2 | 1000 | 21/03/2016
2 | 2 | 2000 | 22/03/2016
3 | 1 | 3000 | 22/03/2016
My code is the following:
$category = "band";
$profiles = DB::table('profiles')
->join('likes', 'profiles.id', '=', 'likes.account_id')
->where('category', '=', $category)
->select('profiles.*', 'likes.likes', 'likes.created_at')
->get();
account_id in the likes table will be the same as id in the profiles table. Also there maybe multiple like records for each profile.
The query just doesn't seem to work and it returns nothing back. I'm using laravel 5.2.
$profiles = DB::table('profiles')
->leftJoin('likes', 'profiles.id', '=', 'likes.account_id')
->where('profiles.category', '=', $category)
->select('profiles.*', 'likes.likes', 'likes.created_at')
->get();

Laravel Has Many Returns a Row even it has a value in relations table

Hi I'm using laravel eloquent for my database query. My Problem is that I can't show the data I wanted to show. I have three tables. Say Users Table, Roles Table and User_Roles table.
Users
id | Name |
1 | John |
2 | Doe |
Roles
id | Name |
1 | Admin |
2 | Employee |
3 | Manager |
User_Roles
id | user_id | role_id
1 | 1 | 2
2 | 1 | 3
3 | 2 | 3
Users has Many Roles that is saved in User_Roles table. My query is "I want to show list of Users that has no Employee roles. In the table I want to show only Doe. How can I make it laravel eloquent.
Hope someone can help!
Define roles relation in User model
public function roles() {
retrun $this->belongsToMany(\Namespace\Role::class);
}
Retrive the role
$role = \Namespace\Role::where('name', 'Employee')->first();
Get the users
$user = \Namespace\User::whereHas('roles', function($query) use ($role) {
$query->where('role_id', '!=', $role->id);
})->get();

Categories