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

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

Related

Laravel update the status in other foreign key table

I have three tables (users, table_1, table_2) and have users table foreign keys in table_1 & table_2 tables.
Users
id
name
email
status (1/0)
created_at
updated_at
Table 1
id
message
status (1/0)
user_id (FK of users)
created_at
updated_at
Table 2
id
about
status (1/0)
user_id (FK of users)
created_at
updated_at
Note: For the explanation, I have used Table 1,2 name.
Now I am updating the status of the user table and the same status update in table_1 & table_2 where the foreign key is a match.
Here I have written individual query for each table:
$users = Users::where('id', $id)->update([
'status' => $status
]);
Table1::where('user_id', $id)->update([
'status' => $status
]);
Table2::where('user_id', $id)->update([
'status' => $status
]);
So is there any way to reduce the query with the eloquent relationship?

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (unfix)

I am using laravel
My Error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bd_name`.`inpatients`, CONSTRAINT `inpatients_ward_id_foreign` FOREIGN KEY (`ward_id`) REFERENCES `wards` (`id`)) (SQL: insert into `inpatients` (`patient_id`, `ward_id`, `updated_at`, `created_at`) values (2010101, 06, 2020-10-14 06:44:12, 2020-10-14 06:44:12))
My inpatient table is here:
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('patient_id');
$table->foreign('patient_id')->references('id')->on('patients');
$table->char('discharged',4)->default('NO'); // YES | NO
$table->unsignedBigInteger('ward_id');
$table->foreign('ward_id')->references('id')->on('wards');
inpatientController
$INPtable = new inpatient;
$INPtable->patient_id = $request->reg_pid;
$INPtable->ward_id = $request->reg_ipwardno;
Inpatient Model
protected $fillable = [
'ward_id','patient_id',
];
public function ward() {
return $this->belongsTo('App\Ward');
}
public function patient() {
return $this->belongsTo('App\Patients');
}
I don't understand what's going wrong here. Please help me.
The error will be mostly because of the table which you referred as foreign key in inpatient table i.e ward table. You first have to enter data in the ward table, and that data you can refer in the child table. If key 6, is not present in the ward table, insert it first into the table, then do the insertion in the inpatient table.
Hope you got it. Thank You :)
My ward table has ward_no also. I have passed ward_no instead of ward id. That's why the error.

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

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

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

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