vendredi 3 avril 2020

save repeated items in laravel pivot table

I am working with laravel and I have these models (a summary) with the following relationships:

Table products
  increment id;
  string    description;

Table materials
  increment id;
  string    name;  

Table material_product
  increment id;
  integer   product_id;
  integer   material_id;
  string    dimension;  

class Product extends Model
{
    public function materials()
    {
        return $this->belongsToMany(Material::class)->withPivot('dimension');
    }
}

class Material extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('dimension');
    }
}

I am using the attach (to save) and sync (to update) the data of my pivot table, the problem is that in my business model I need to be able to save repeated items, for example:

products
+-----+--------------+
|  id | description  |
|-----|--------------+
|  1  | dining table |
+-----+--------------+

materials
+-----+------+
|  id | name |
|-----|------+
|  1  | wood |
+-----+------+

material_product
+-----+------------+-------------+-----------+
|  id | product_id | material_id | dimension |
|-----|------------+-------------+-----------+
|  1  |    1       |      1      |   10 x 2  |
+-----+------------+-------------+-----------+
|  2  |    1       |      1      |   5 x 3   |
+-----+------------+-------------+-----------+

so none of these methods works for me since if I send more than 1 repeated material, only one is attached to my database, how can I do this? some idea?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire