Laravel 5.3 query to get results from 4 tables which has connections via Foreign Key - laravel

I'm using Laravel 5.3. I've 4 tables.
Default Users table. Departments, Position, Employees tables.
Users table has ID | Email | Password
Departments table has ID | Department | User_Id - Here User_Id is foreign key comes from Users table's ID
Positions table has ID | Position | Department_Id - Here Department_Id is foreign key comes from Departments table's ID
Employees table has ID | Employee | Position_Id - Here Position_Id is foreign key comes from Positions table's ID
User can have multiple Departments. Departments can have multiple Positions, Positions can have multiple Employees. So, if user is different, how can i retrieve all data from all 4 tables which that user had created?

You can use nested eager loading:
$departments = Department::where('user_id', $id)
->with('positions', 'positions.employees')
->get();
Another way is to build simple queries:
$departments = Department::where('user_id', $id)->get();
$positions = Position::whereIn('department_id', $departments->pluck('id'));
$employees = Employee::whereIn('position_id', $positions->pluck('id'));

Related

Pass parent id while inserting in 2 columns with one-to-one relation

I have 2 columns with one-to-one relation users and doctors:
Users
_____________
| id | name |
|____|______|
| 1 | John |
|____|______|
Doctors
_____________________
| id | dep | user_id |
|____|_____|_________|
| 1 | 2 | 1 |
|____|_____|_________|
User model has this function that returns the doctor with relation:
public function doctor(){
return $this->hasOne(Doctor::class);
}
Inserting data:
$valdiated = $request->validated();
$userData = [
'name' => $valdiated['name'],
];
$doctorData = [
'dep' => $valdiated['dep'],
];
$newUser = new User();
$newUser->insert($userData);
$newUser->doctor()->insert($doctorData);
But I'm getting this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db`.`doctors`, CONSTRAINT `doctors_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `doctors` (`dep`) values (2))
Is there a way to insert the user_id into doctors table or I have to query the database and get the last id?
You should use create() instead of insert since it will return a instance of the new Model that you just created. Then you will use the doctor() to create a associated to the doctor table.
$newUser = User::create($userData);
$newDoctor = $newUser->doctor()->create($doctorData);
dd($newUser,$newDoctor); //Just to check if the data is inserted.
I think the issue is using ->insert(); that doesn't perform any kind of linking logic on the associated Model, so user_id would be null, as it is not present in $doctorData.
You can use ->create() instead:
$newUser = User::create($userData);
$newUser->doctor()->create($doctorData);

How to access to user data through intermediate table (hasOneThrough / hasManyThrough)

For a job posting application, I have three tables, which shortly are defined as:
applications:
id as primary key
job_offer_uuid as external key
job_offers:
uuid as primary key
user_id as external key
users:
Just laravel normal users table with id as primary key
Because I need to notify job_offer owner (a member of User model) any time that an application is registered, I'm trying to create a hasOneThrough or hasManyThrough relationship from applications to users, but without success for the moment.
For clarification:
User model only hosts users that publish job offers, and any user can publish many job offers. There is not applicants in users table
Based on my understanding of eloquent documentation (https://laravel.com/docs/8.x/eloquent-relationships#has-one-through), my actual code in Application model is:
public function publisher()
{
return $this->hasOneThrough(User::class, JobOffer::class, 'job_offer_uuid', 'user_id');
}
But it fires an SQL error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'job_offers.job_offer_uuid' in 'field list' (SQL: select `users`.*, `job_offers`.`job_offer_uuid` as `laravel_through_key` from `users` inner join `job_offers` on `job_offers`.`id` = `users`.`user_id` where `job_offers`.`job_offer_uuid` in (1)
using hasManyThrough instead, I got an identical error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'job_offers.job_offer_uuid' in 'field list' (SQL: select `users`.*, `job_offers`.`job_offer_uuid` as `laravel_through_key` from `users` inner join `job_offers` on `job_offers`.`id` = `users`.`user_id` where `job_offers`.`job_offer_uuid` in (1))
I can get accurate results using pure SQL with a sentence like this:
select applications.id, applications.job_offer_uuid, job_offers.uuid, job_offers.user_id, users.id, users.name, users.email from `applications` inner join job_offers on `applications`.`job_offer_uuid` = `job_offers`.`uuid` join users on job_offers.user_id = users.id where `applications`.id = 1
Any video or tutorial that I found related to this point are using the final table with a foreign key to the intermediate table, and thats means my User model should have a foreign job_offer_id key, but that make no sense to me.
Any clarification should be truly appreciate. Regards!
You are doing it wrong. You have to define relationship in User Model as follow:
public function publisher()
{
return $this->hasOneThrough(
Application::class,
JobOffer::class,
'user_id', // Foreign key on job_offers table
'job_offer_uuid', // Foreign key on applications table
'id', // Local key on user table
'uuid' // Local key on job_offer table
);
}

Lavavel Eloquent: Relationships with 5 table

I have an app consisting of these tables
users
id
name
user_location
id
user_id
cities_id
cities
id
state_id
country_id
name
states
id
country_id
name
countries
id
name
Then how to get relationship this five table?
you have to create a many-to-many relationship between tables and use pivot table to show the relationship between table rows using foreignId

relational database in eloquent laravel

hay i have table schema like this
table transaction_fueler
id | code | user_id |user_name| ref_code | area_name
table user_community
user_id | community_id
table user_community is pivot table from table users and community
in table transaction_fueler i want to get community_id from table user_community, depends on user_id* in **transaction_fueler how to get community_id depends on user_id in table transaction_fueler ??
i stuck this.. thanks
i recommend joining the two tables and select the columns you want:
$values = DB::table('transaction_fueler')
->join('user_community', 'user_community.user_id', '=', 'transaction_fueler.user_id')
->select('transaction_fueler.*', 'user_community.community_id')->get();

Linq to Entities: .Clear() does not delete relation row, only relation column value

I have a 'users' and 'notifications' tables.
The tables definition are:
users notifications
------- -------------
ID (PK) ID (PK)
Name Name
users_ID (FK / Relation)
When I do:
MyUserEntity.notifications.clear();
MyContext.SaveChanges();
The users_ID column value(s) for the corresponding user entity are set to NULL, but I want the rows to be deleted.
What am I missing?
Thanks!
Try
foreach(var notification in MyUserEntity.notifications.ToList())
{
MyContext.DeleteObject(notification);
}
MyContext.SaveChanges();

Resources