How to do insert 1 to 1, with four tables in laravel

2

I'm working with a database already populated. It has four tables ( Aluno , clinico , Familia and TipoCompulsao ), where Aluno receives foreignkey from the three tables;

Model student

class Aluno extends Model{

public $timestamps = false;
protected $fillable =[
                    'Nome','Sobrenome','Cpf','Email','Altura','Telefone','Endereco'
];

public function clinico(){


    return $this->belongsTo(Clinico::class);
}
public function familia()
{

    return $this->belongsTo(Familia::class);
}
 public function tipocompulsao()
{
    return $this->belongsTo(Tipocompulsao::class, );

Clinical model

class Clinico extends Model
{
    public $timestamps = false;
    protected $fillable=[
        'hasAnsiedade',
    'hasInsonia',
    'hasHipertensao',
        'hasDiabetes', 
    'hasAlergias', 
    'hasDisturbiosOncologicos',
    'hasProblemasRenais', 
        'hasMenopausa', 
    'hasHipotiroidismo',
    'hasColesterol', 
    'hasFigado', 
    'hasOutros' 
    ];

    public function aluno() {
          return $this->hasOne(Aluno::class );

      }
}

model family

   class Familia extends Model
{
      public $timestamps = false;
      protected $fillable=[

         'hasObesidade',
    'hasDoencaRenal',
        'hasHipertensao', 
        'hasColesterolGorduraFigado'  

      ];
      public function aluno() {
          return $this->hasone(Aluno::class);

      }
}

Tipocompulsao

    class Tipocompulsao extends Model{

      public $timestamps = false;
      protected $fillable=[
        'hasCompulsaoDoce',
    'hasCompulsaoSalgado'  
      ];

      public function aluno() {
          return $this->hasone(Aluno::class);

      }
}

** Controller to save dataform **

public function test(){

        $dataform=([



            'Nome'=> 'bi',
            'DataNascimento'=>'21-01-1999',
            'Sobrenome'=>'carlos',

        'hasHipertensao'=>'1',

            'hasObesidade'=>'1',
        'hasDoencaRenal'=>'1'



            ]);
    $tipoco=Tipocompulsao::create($dataform);
    $clinico= Clinico::create($dataform);
    $familia=Familia::create($dataform);


    $aluno=$familia->aluno()->create($dataform);
    $aluno=$clinico->aluno()->create($dataform);
    $aluno=$tipoco->aluno()->create($dataform);

I'm using this script to save; the main problem is that it generates three results for me in the table Aluno a id of each of the other tables for each row, while a single result only one result.

    
asked by anonymous 06.11.2018 / 14:50

1 answer

2

Friend, you have to give a revised one. In your code there are some writing errors .. Ex. There are models that have anything tiny.

To link 1 to 1, use the 'associate':

$clinico = Clinico::create($dataform);
$familia = Familia::create($dataform);


$clinico->familia()->associate($familia);
$clinico->save();

To unlink:

$clinico->familia()->dissociate();
$clinico->save();

This directs the foreign key to null.

    
06.11.2018 / 18:47