Laravel 5.8 - We can do sync
in a table pivot
without the field id
?
The Eloquent ORM Framework contained in Laravel has this command Sync which has in its documentation the following text:
google translation:
That is, in a ratio of many to many the function of this method is to adjust the ratio in the table pivot
where the codes to be deleted and the codes to be inserted are made transparently. In a real analogy is done in the method Sync one detach(that removes registration from the relationship) and then a attach(which adds registration to the relation).
In the relation table, the model presented in the documentation does not show id
, nor is it necessary, maybe extra fields with some kind of configuration can coexist, but the primary key composed of the two relations.
Example:
An author may be contained in several books and vice versa book may have several authors:
class Autor extends Model
{
protected $table = 'authors';
protected $primaryKey = 'id';
protected $fillable = ['nome'];
//Relacionamento. N:M
public function livros()
{
return $this->belongsToMany('App\Livro',
'autor_livros',
'autor_id',
'livro_id'
);
}
}
class Livro extends Model
{
protected $table = 'books';
protected $primaryKey = 'id';
protected $fillable = ['titulo'];
public $timestamps = false;
//Relacionamento. N:M
public function autores()
{
return $this->belongsToMany('App\Autor',
'autor_livros',
'livro_id',
'autor_id'
);
}
}
Using the method Sync:
$livro = Livro::find(1);
$livro->autores()->sync(array(1,2));
or
$autor = Autor::find(1);
$autor->livros()->sync(array(3,4));
Ref.
i don’t have model for pivot table. I could create it. But vc has some suggestion using Sync method and no model?
– zwitterion
I put using attach and detach, I believe it is simpler than using Sync in this case.
– André Lins