Ad

How To Handle Relationship With Two Foreign Keys From One Table In Eloquent?

I have table Users and Specialization. :

Users:
id (primary, auto increment)
user_id (unique)
hex_id (unique)
status (boolean)

Specialization:
id (primary, auto increment)
user_id (foreign key from users)
hex_id (foreign key from users)
description (text)

What should be my controller relationship type between users and specialization? is it one is to one? or or one is to many?

The issue is when I add data to Specialization table during form submit my user_id gets auto fill from the relationship but nothex_id, giving me the error:

..hex_id doesn't have default value..

Is this possible to auto fill both foreign keys in Specialization table using relationship only?

PS I cannot change how the schema was structured.

Ad

Answer

we can just add hax_id value before record is created, within your Specialization model you can add function like below. (make sure remove all validations on hax_id field)

we can use beforeCreate event of modal for this. if user_id are hax_id same then we can just assign it, if in your case it is different then you can fetch user from DB using user_id and access its hax_id and use it. please check below code.

use \Backend\Models\User;

// inside your `Specialization` model
public function beforeCreate()
{
    $this->hax_id = $this->user_id;
    // or if its not the case and user_id and hax_id are not same then.
    // $user = User::find($this->user_id);
    // $this->hax_id = $user->hax_id;
}

in this way hax_id will automatically added to your record. beforeCreate will work only on record creation, you can replace beforeCreate with beforeSave to make this happen all the time create and update.

if any doubt please comment.

Ad
source: stackoverflow.com
Ad