(Laravel / Eloquent) How to join 4 tables to make 1 query - laravel

I'm new at Laravel and I want some help with a Query. Here is my situation. I have 4 tables:
users (id, email, password.....)
user_profile (id, first_name, last_name,........, user_id)
companies (id, name,.......)
policies (id, policy_num, exp_date,........., user_id, company_id)
The table user have 5 users and every user have 10 policies. The table company have 3 companies.
$user_data=User::select('*')
->with('profile','policies')
->where('id', '=', $userId)
->first();
This code is working good, it retrieves the all the users and user_profile fields and all the policies(10) of this user with as you can see in this image, and I can show the user the details of the products on a home page.
I want to instead of appear the company_id from the policies table appears the name of the company from the company table.
Any help is appreciated.

Thank you for your answer ceejayoz, i already did.
User
public function profile()
{
return $this->hasOne('UserProfile');
}
public function policies()
{
return $this->hasMany('Policy');
}
Policy
public function company()
{
return $this->hasOne('Company');
}

Related

Laravel - Find value is available in relationship

I need to check if the given user_id, location_id, and sub_location_id is belongs to the user on user_locations table. Based on this I need to give login permission to the user for the specific site.
Currently, I have the written code like below. But, don't know how to check the condition.
User::select('id')->with('user_locations:location')->where('user_id',$request->user_id)->get();
I need to put these conditions
is user found and active?
if user active. Then find the given sub location is tagged for the user.
if sub location found, then is the sub location active?
Below are the table structure.
Users Table
id (PK, AI),
user_id (UQ),
password,
status, ("Y"=> Active, "N"=> Inactive)
//other fields
public function user_locations(): HasMany
{
return $this->hasMany(user_locations::class);
}
User_Locations Table
id (PK, AI),
user_id (FK),
location_id (FK),
sub_location_id (FK),
status ("Y"=> Active, "N"=> Inactive)
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
I think you need to check relation existing
You can try this way for find user model
User::select('id')
->with('user_locations:location')
->where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->get();
If you want just to check user existing you can try this
User::where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->exists();
You can read mode about this here

Laravel 5.2 Eloquent ORM to get data from 3 tables

I have the following tables. users, user_details and client_teams. Each user has one details and each user can have many teams. schema for users:
id, name, email,parent_user_id
user_details:
id, user_id, client_team_id
client_teams:
id, user_id, team_name,status
In user_model i have the following relations:
public function userDetails(){
return $this->belongsTo('App\Models\UserDetails','id','user_id');
}
public function clientTeamList(){
return $this->hasMany('App\Models\ClientTeams','user_id','id');
}
In user_details model i have the following relation:
public function clientMemberTeam(){
return $this->belongsTo('App\Models\ClientTeams','client_team_id');
}
I want to be show the list of users who have a specific team ID and created by a specific user. The query that i am using is this:
$userCollections=Users::where([
['users.status','!=','DELETE'],
['users.parent_user_id',$clientId],
['users.id','!=',$loginUser->id]
])
->with([
'userDetails'=>function($query) {
$query->where('client_team_id',1);
}
]);
This is giving me all records for this user, Whereas i want to match by client_team_id and user_id
You need to use whereHas and orWhereHas methods to put "where" conditions on your has queries.
Please look into https://laravel.com/docs/8.x/eloquent-relationships
$userCollections = Users::where([['users.status', '!=', 'DELETE'],
['users.parent_user_id', $clientId],['users.id', '!=', $loginUser->id]
])
->whereHas('userDetails' => function ($query) {
$query->where('client_team_id', 1);
})->get();

Laravel hasManyThrough in depth

I have been looking at documentation regarding the hasManyThrough relationship in Laravel, and fro some reason I am struggling with it as the documentation makes it look simple (maybe I am overthinking it)....
I have three Models tables at the moment:
-User (extends authenticatable)
id,
name,
surname,
email,
password.
-Order
id,
user_id,
name,
unit,
qty
-Product (i need to add a qty table to show how many is ordered).
id,
order_id,
name,
unit,
description,
family
My Products model is used by Admin to CRUD products.
Please can someone explain to me how I will be able to display to admin which user made an order, and what does the order consist of.
I also want to display to the user a 'order history'..
Please will anyone be able to assist..
UPDATE
-order_product
id,
order_id,
product_id
quantity
product controller:
public function orders()
{
return $this->belongsToMany('App\Order')->withPivot('quantity');
}
order controller:
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity');
}
I think you need create one more table like order_details
-User (extends authenticatable)
id,
name,
surname,
email,
password.
-Order
id,
user_id,
name,
unit,
qty
-Product (i need to add a qty table to show how many is ordered).
id,
name,
unit,
description,
family
-Order_detail(Store product_id, order_id (You can put qty to this table))
id,
order_id,
product_id
It is many to many to relationship show you'll have to create one another pivot table named
order_product with fields
-id
-order_id
-product_id
-quantity
and in your Order table Model define relationship as
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity');
}
and in your Product table Model define relationship as
public function orders()
{
return $this->belongsToMany('App\Order')->withPivot('quantity');
}
to Retrieve data
$order= App\Order::find(1);
#foreach ($order->products as $product)
echo $product->pivot->quantity."<br>";
#endforeach

Laravel Eloquent - many to many with where for the pivot table

I'm trying to see what the best way to do the following.
I have 3 tables: users, items and item_user.
users and items table are pretty generic, id and a few columns to hold whatever data.
item_user table has the following structure
id
item_id
user_id
user_type [ 1 - Owner | 2 - Follower | 3 - Something else ]
Relationships:
Each Item has 1 Owner (user type)
Each Item has many followers
Each User can own many Items
Each User can follow many Items
I would like to have the Owner and Followers be the Users table so I don't need to replicate user data. I created a pivot table of item_id, user_id and user_type to hold these relationships.
So the question is how to I do this in Laravel Eloquent?
Item Model looks like:
public function user() {
return $this->belongsToMany('Users');
// This isn't actually correct since it belongs to only one User but not sure how to specify a where user_type = 1;
// return $this->belongsTo('User');
}
User Model looks like:
public function item() {
return $this->hasMany('Item');
}
Thanks!
You can just append the condition to your belongsToMany declaration:
public function user() {
return $this->belongsToMany('Users')->where('user_type', 1);
}
This will return only the User entries that have user_type = 1 in your pivot table. And just to make it more clear you could name the method owner() instead of user() to reflect the added condition.

How to get user's menu that has active modules in Laravel 4 with Eloquent?

I have tables to store user's menu like below:
Table: modules
id
name
status (will have values: active / inactive)
Table: menus
id
module_id
link
Table: menu_user
user_id
menu_id
join
Table: users
id
name
password
The relationship will be like:
[users]-<menu_user>-[menus]-[modules]
Modules has many Menus; and relationship between Users and Menus is many to many.
I only can get user's menu:
$data = User::with('menus')->where('id', 2);
Any how with Eloquent way that I want to have the users's menu where the modules has active status?
Another approach would be to come from the User end and use a nested relationship to the module, eg.
User::where('users.id', 1)
->with(array('menus.module' => function($query) {
$query->where('modules.status', '=', 'active');
})
)->get();
This is dependent on the following in the Models:
User
public function menus()
{
return $this->belongsToMany('Menu');
}
Menu
public function module(){
return $this->belongsTo('Module');
}
Module
public function menu(){
return $this->hasMany('Menu');
}
Glen

Resources