Import multiple ids in one record

Viewed 52

I can add on item which is 'product_id' in each import my question is How to add multiple product ids with multiple quantities in the same record and not one id ?

Schema::create('imports', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('supplier_id');
            $table->bigInteger('branch_id');
            $table->bigInteger('product_id');
            $table->bigInteger('quantity');
            $table->double('cost',null,2);
            $table->timestamps();
        });

Controller

$import = new Import();
        $import->supplier_id = $request->supplier_id;
        $import->branch_id = $request->branch_id;
        $import->product_id = $request->product_id;
        $import->quantity = $request->quantity;
        $import->cost = $request->cost;
        $import->save();
1 Answers

As you want to add multiple products associated to one import so, you have to use one-to-many relation. You need to create another model ImportProduct with a relation to Import model like so

class ImportProduct extends Model 
{

    ...

    function import()
    {
        return $this->belongsTo(Import::class);
    }

    ...
}

And in your Import model you will add

function products()
{
   return $this->hasMany(ImportProduct::class);
}

In your import_products migration you will add

...

$table->id();
$table->bigInteger('import_id');
$table->bigInteger('product_id');
$table->bigInteger('quantity');

...

You will remove product_id and quantity from imports migration.

Now in your controller you can add one import with multiple products using products() relation from Import model.

$import = new Import();
$import->supplier_id = $request->supplier_id;
$import->branch_id = $request->branch_id;     
$import->cost = $request->cost;
$import->save();

// $import->products()->associate($products);

//foreach ($products as $product) {
//    $import_product = new ImportProduct();
//    $import_product->import_id = $import->id; 
//    $import_product->product_id = $product->id;
//    $import_product->quantity = $product->quantity;
//    $import_product->save();  
//}

Related