Doubt relationship One to Many

Asked

Viewed 45 times

0

Talk guys, all right? Next, I’m banging head with the Seed of my BD in Aravel, I believe that those who have more experience with the framework know how to solve.

I have the Person model with One to Many relationship for another two (Professional and Client). When it comes to migration, it turns out that registered people end up being professionals and customers at the same time, as they carry the same ids, as I determine, for example, 10 id record from 1 to 5 will be clients and id 6 to 10 will be professionals?

class Pessoa extends Model {

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

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

Model Profissional

class Profissional extends Model
{
public function pessoa(){
    return $this->belongsTo('App\Pessoa');
}

Model Cliente

class Cliente extends Model
{
public function pessoa(){
    return $this->belongsTo('App\Cliente');
}
}

My Seed ( Here the error >:p )

factory(App\Pessoa::class, 10)->create()->each(function ($u) { 
$u->cliente()->
save(factory(App\Cliente::class)->make());
$u->profissional()->
save(factory(App\Profissional::class)->make());  
});
  • Another idea, but I did not test if it would work, what would be the possibility of putting a conditional there inside that Factory and according to the $id, send to the correct rule?

1 answer

0

You can make the processes separate, since the Person is never client and professional at the same time. Example:

 factory(App\Pessoa::class, 5)->create()->each(function ($u) { 
    $u->cliente()->save(factory(App\Cliente::class)->make());
 });

 factory(App\Pessoa::class, 5)->create()->each(function ($u) { 
    $u->profissional()->save(factory(App\Profissional::class)->make());  
 });

You could also do the Factories within a for, with the count and the rules you quoted, but I think it will be more boring to keep.

Browser other questions tagged

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