How to get count from pivot table laravel? - laravel

I have two tables,
User cities user_cities
id name id name user_id city_id
1 aaa 1 cityA 2 1
2 bbb 2 cityB 2 3
3 ccc 3 cityC 1 2
3 3
3 2
Now i am filtering the user by cities. I am having the city_id = 2. So that i have to get the count of users belongs to the city_id 2.
How can i get that using laravel eloquent

As you describe in your answer you have the third table user_cities.
If you have table user_cities then count user like
DB::table('user_cities')->where('city_id', '2')->count();

There are different ways to do this, check https://laravel.com/docs/5.8/queries
But a simple way of doing it could be:
UserCity::whereCityId(2)->count();
Or:
UserCity::where('city_id',2)->count();

If you have set correctly the relationship between them, you can do something like that:
City::where('id', '=', 2)->withCount('users')->get();
It will place a {relation}_count column on your resulting model, and thus you can call it like a property: $city->users_count
Edit: For further information, you can check the official documentation.

Try this query :
$count = City::where('id', 2)->whereHas('users')->count();

Related

mysql ORDER BY depending on column

I have the table client_contacts like:
id
client_id
contact_type_id
data
1
1
3
johndoe#gmail.com
2
2
4
+999 999 999
3
..
..
....
In my contact_types table I have the following types:
id
description
1
address
2
fixed phone
3
email
4
mobile
I want the ability to sort all the contacts that are in the data column and by that, the possibility to sort with the contact_type_id. How to do it in Laravel 8 with Eloquent\Builder? I am using paginate as well.
Some uses:
Sort ASC all the emails and furthermore the possibility to sort two contact_types like fixed phone ASC and mobile DESC.
In my client model, I have hasMany() to the client_contacts model.
According to documentation:
MYSQL:
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_field
LARAVEL:
https://laravel.com/docs/9.x/queries#orderbyraw
You can Add This Quote Of Code:
->orderByRaw("FIELD(contact_types.description, 'addresses', 'fixed phones', 'email', 'mobile') ASC")

Laravel sum/count nested relation

i have a problem with simple relations.
Tables looks like that:
table players
id user_id game_id
1 2 1
2 5 1
3 3 1
4 4 2
5 2 2
table games
id result (win or lose)
1 1
2 0
What i need in result is:
Players Wins Losses
John 3 2
Philip 2 2
Jack 1 3
I tried alot of queries but i cant get proper result.
This one
`"select * from `players` inner join `games` on `players`.`game_id` = `games`.`id`"`
This one is best i can do, but its raw and no idea how to rewrite it to DB:: or Eloquent. And its not grouping anyway.
you can directly count from relation with model.
$category = Category::find($id);
$category->children->count();

How to get product list related to other sale transaction count in Laravel?

I'm a newbie in Laravel and working on a small e-commerce project. I need to get products list that related to transaction count in the transaction table. Below is my demo data.
tb_product:
product_id product_name
1 A
2 B
3 C
tb_transaction:
transaction_id product_id
1 2
2 1
3 2
4 2
5 1
6 3
From tb_transaction. I have sale list as below
B = 3sales, A =2sales, C=1sale
I need to generate Laravel eloquent result like [{B...},{A...},{C...}] (count from max to min). I had tried some from google but no luck. Appreciated for advice, Thanks.
Try the below query,
DB::table('tb_product')
->select('tb_product.product_id', 'tb_product.product_name', DB::raw("count('tb_transaction.product_id') as salesCount"))
->join('tb_transaction', 'tb_transaction.product_id', 'tb_product.product_id')
->orderBy('salesCount', 'DESC')
->groupBy('tb_product.product_id', 'tb_product.product_name')
->get()

Select and sum multiple columns for statistic purposes with Laravel query

I have one table scores where I have saving users scores. It's looks like this
table `scores`
id | points | user_id
1 5 1
2 2 1
3 4 1
4 1 3
5 10 2
I want to select each user, sum his points and show as a ranking. The result from above should be
user_id | points
1 11
2 10
3 1
The query with which I came up is
$sumPoints = Scores::select( \DB::raw("sum(points) as numberOfPoints"), \DB::raw("count(id) as numberId"))->groupBy("user_id")->first();
The problem is in ->first() because it's return only one result.. it is working as must. If I try to use ->get() instead I've got Undefined property error. How should I use this?
The query which is working in phpmyadmin
SELECT count(id) as numberId, sum(points) as numberOfPoints FROM `points` GROUP BY `user_id`
You can use something like this
$sumPoints = Scores::select( \DB::raw("sum(points) as numberOfPoints"), \DB::raw("count(id) as numberId"))->groupBy("user_id")->get();
foreach($sumPoints as $point){
dd($point); //OR dd($point->numberOfPoints)
}

Laravel Relation Many to Many

I'm using laravel and sentinel (Sentry) that default using users, groups, and users_groups database table
users
-----------------
id name
1 user
2 user
3 admin
groups
-------------------
id name
1 Users
2 Admins
users_groups
--------------------
user_id group_id
1 1
2 1
3 1
3 2
i define the relation on laravel model and it's work fine when i try to print
$users = Group::find($id)->user;
but how to print just user only?
$users = Group::where(array("name"=>"Users"))->get()->user;
it's still show all data include the admins, i just want to show user only, how to do this?
i know the problem because at users_groups table admin have Users id too..
Please someone help me. It's verry confusing
You can use with to get the data of specified relation as below :
$users = Group::with('user')->find($id);
This will return data of group with user.
If you just want a data of only user table you have to change the query and rather than using model Group you have need to query on User model something like below:
$users = User::where('group_id', $groupId);
http://laravel.com/docs/5.1/eloquent-relationships
http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_with

Resources