How to insert an intermediate table in laravel?

0

having the following tables-migrations in laravel:

Table person

Schema::create('personas', function (Blueprint $table) {
    $table->increments('id');
    $table->string("nombre");
    $table->string("apellidom")->nullable();
    $table->string("apellidop")->nullable();
    $table->date("fecha_nacimiento")->nullable();
    $table->string("ci")->nullable();
    $table->enum("sexo",["masculino","femenino"])->defautl("masculino");
    $table->string("celular")->nullable();
    $table->string("direccion")->nullable();
    $table->enum("tipo",["trabajador","paciente"])->default("trabajador");
    $table->timestamps();
});

Table Charges

Schema::create('cargos', function (Blueprint $table) {
    $table->increments('id');
    $table->string("nombre");
    $table->text("descripcion")->nullable();
    $table->timestamps();
});

Intermediate table apersona-cargos :

Schema::create('persona_cargo', function (Blueprint $table) {
    $table->integer("persona_id");
    $table->integer("cargo_id");
    $table->date("fecha");
    $table->timestamps();
});

Being the relationship of many to many between Person and Charges .

$persona=new Persona($request->all());
$persona->save();
$cargo=new Cargo($request->all());
$cargo->save();
//aqui cual seria el codigo siguiente?
  

How do I insert the intermediate table persona_cargo ?, since it does not have a model.

    
asked by Shassain 16.09.2018 в 13:00
source

1 answer

1

To insert in the intermediate table, just call the relationship method and then access the attach() method:

$persona->cargos()->attach($cargo->id);

You can also send an array of ids:

$persona->cargos()->attach([1, 2, 3]);

If your intermediate table has additional columns to foreign keys, you can insert it like this:

$persona->cargos()->attach($cargo->id, ['expira' => $expiracion]);

To synchronize related records you can do the following:

$persona->cargos()->sync([1, 2, 3]);

Any id that is not in that array will be removed from the intermediate table that corresponds to the relation, thus, only the charges with ids: 1, 2 and 3 would be related.

    
answered by 17.09.2018 / 19:53
source