Relate tables with laravel

1

I want to relate two tables, and keep the two ids in another table to relate them, for example:

I'm logged in with a user, and I create a product, how do I add the id of the user and the id of the product in an additional table if the product has not yet been created and I do not have its id? Without using the method of adding +1 to the last id of the product since it can give conflict if there is more than one user creating products.

    
asked by Alex G. 19.09.2017 в 10:36
source

1 answer

0

Short answer you can not do what you say, you must first create the product, after that it is easy to relate them, the most viable option is to first create the corresponding migration, I recommend you follow the conventions of Laravel .

Assuming that your two tables are users and productos on your command line create a%% migration%.

On your migration:

Schema::create('producto_user', function (Blueprint $table) {
    $table->integer('producto_id')->unsigned();
    $table->integer('user_id')->unsigned();

    $table->foreign('producto_id')->references('id')->on('productos')
                ->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');

    $table->primary(['producto_id', 'user_id']);
});

Make sure that in the migrations both php artisan make:migration create_producto_user_table and users the productos is increible, if you create the migration by means of a command id it will appear automatically, if you do not add at the beginning of the migration artisan it should look something like this:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    //Las demás tablas
...
Schema::create('productos', function (Blueprint $table) {
    $table->increments('id');
    //Las demás tablas
...

On your models:

class User extends Authenticatable
{
...
    public function productos()
    {
     return $this->belongsToMany(Producto::class);
    }

//

class Producto extends Model
{
...
    public function usuarios()
        {
         return $this->belongsToMany(User::class);
        }

In the $table->increments('id'); of your choice in which you are going to create the product and associate it with the user:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Producto;

class MainController extends Controller
{
    public function ejemplo(Request $request)
    {
        $producto = new Producto;
        $producto->nombre = $request->nombre;
        ... #Y todos los datos recabados con tu form.
        $producto->save();

        //Al momento de pasar la función save() a la variable $producto 
        //se guardan los datos en la DB y te retorna el id
        //de esa forma puedes pasarle el id a la tabla intermedia

        //Asumo que el user que creo el producto será el actualmente logeado
        $user = Auth::user(); //De no ser así aquí haces el query para encontrar el user
        $user->productos()->attach($producto->id);
        //Aquí agregaste el id del producto 
        //y se asume el id del usuario para guardar 
       //ambos en la tabla intermedia

    }
}

Ready, you already have the relationship.

    
answered by 19.09.2017 / 19:23
source