Insertion in the bank with relationship N : M

Asked

Viewed 102 times

2

I need to insert users into my database MySQL already with the relationship N:M, but I don’t know how to do it.

Migrate:

Schema::create('usuarios', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nome');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

 Schema::create('rotas', function (Blueprint $table) {
        $table->increments('id');
        $table->string('action');
        $table->timestamps();
    });

 Schema::create('usuarios_rotas', function (Blueprint $table) {
        $table->integer('usuario_id')->unsigned();
        $table->foreign('usuario_id')->references('id')->on('usuarios');
        $table->integer('rota_id')->unsigned();
        $table->foreign('rota_id')->references('id')->on('rotas');
    });

Model:

class Usuario extends Model
{


 protected $fillable = [
        'nome', 'email','password'
    ];

public function rotas() {

    return $this->belongsToMany(Rota::class);
}
}

class Rota extends Model
{

protected $fillable = [
    'rota'
];

public function usuarios() {

    return $this->belongsToMany(Usuario::class);
  }
}
  • 1

    Insert the user, take the generated id. Insert the routes, take the generated ids. Insert all in users_routes.

  • how will I insert everything into users_routes ?

  • ready edited the post

  • 1

    @Andersoncarloswoss, or create a database database that receives a new user and new routes and makes this connection

  • ah blz man, I’ll do a search

  • I wrote these days as it should be done for the standard convention, if you have already missed the name of the intermediate table that should be rotated ...

  • Related: https://answall.com/questions/274497/como-name-tabela-pivot-many-to-many/274509#274509

Show 2 more comments

1 answer

2


In Laravel, it’s pretty simple to do this. If you know the user ID and the route ID, just use the method attach to do this:

Example:

 Usuario::find($usuario_id)->rotas()->attach($rota_id);

Browser other questions tagged

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