Improve banking of related entities?

Asked

Viewed 36 times

2

I have in the database the tables User, Professional and Address. The foreign key of User is in Professional and foreign key of Professional is in Address. I need to register a professional, who is a user and has an address.

Model User:

public function profissional()
{
    return $this->hasOne('App\Profissional', 'users_id');
}

Model Profissional:

public function endereco()
{
    return $this->hasOne('App\Endereco');
}

public function user()
{
    return $this->belongsTo('App\User', 'users_id');
}

Model Address:

public function profissional()
{
    return $this->belongsTo('App\Profissional');
}

The way I found to insert the professional into the bank along with the other entities was this:

$user = new User($userData);
$profissional = new Profissional($profissionalData);
$endereco = new Endereco($enderecoData);

$user->save();
$user->profissional()->save($profissional);
$profissional->endereco()->save($endereco);

The code is working normally, but I believe there are better ways to do the same thing. I would like alternative solutions or improvements that can be made in this code.

1 answer

2


It’s just like you did, it can be done to create like this too:

$user->create(array())
     ->profissional()->create(array())
     ->endereco()->create(array());

but its logic is within the standard of Laravel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.