Accessing attributes from multiple different relationships in a CRUD Eloquent Laravel 5.7

Asked

Viewed 208 times

1

Guys I have a structure like this model (Modelo apenas ilustrativo) and want to know how I can access the data of the whole relationship to make a insert/update in these tables with the data received from a form, being that I can give a select with LEFT JOIN in all these tables using a query with DB::raw, but I want to know how to do this only with eloquent methods. From file to file:

Modelo do Banco de Dados

Where as you can see one Processo has only one solicitacao and vice versa, one solicitacao may have N boxes and a box can be in N solicitacoes, whereas one box may have N arquivos.

My Model Process would look like this:

public function processo_solicitacao (){
 return $this->belongTo(Solicitacao::class, 'id_solicitacao', 'solicitacao_id');
}  

My Model request like this:

public function processo (){
 return $this->hasOne(Processo::class);
}  

My model box like this:

public function solicitacoes (){
 return $this->belongsToMany(Processo::class);
}
public function arquivos(){
 return $this->hasMany(Arquivo::class);
}

My Model file like this:

public function solicitacoes (){
 return $this->belongsTo(Box::class, 'box_id', 'id_box');
}

From now on I appreciate any help!

1 answer

1


As long as your relationships are correct, you can call the statistical method create of each model, in an order that you have all the necessary data.

Example:

$solicitacao = Solicitacao::create([ 'info1' => 'valor1' ... ]);
$box = Box::create([ 'info1' => 'valor1' ...]);
$box->associate($solicitacao); // ou
$box->associate($solicitacao->id);
$box->save();

And so on and so forth...

  • associate() in a relation N:N ? It wouldn’t be $solicitacao->attach($box); $box->associate($arquivo); ?? I get lost in the relationships of the Aravel =(

  • No, the Associate() is for a 1:N or 1:1 relationship. N:N you have other methods, like attach([ id1, id2...]), etc... It was just an example, I didn’t notice that this was an N:N. Sorry for my example.

  • Quiet, I understood then, I have to fill all the tables individually and then leave relating =)

  • 1

    Exactly, remember that the method Model::create and Model::update run a save, if in your table the id’s are not null, will make an exception. $model = new Model; $model->attribute = $value; .... $model->attach() // ou $model->associate().

Browser other questions tagged

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