Laravel is a lot for many

I use many, many relationships. I want to set two values ​​for this attribute.

product,

attribute_product => product_id,attribute_id,value

enter image description here

I know this is wrong, but I want to show you what I want

$product->attributes()->sync([
            1 => [
                'value' => 'sky'
            ],
            1 => [
                'value' => 'night'
            ],
        ]);

Update 2

Schema::create('attribute_product', function (Blueprint $table) {

$table->unsignedInteger('product_id');
$table->unsignedInteger('attribute_id');
$table->text('value')->nullable();
$table->integer('devalue_id')->nullable(); // value id 

$table->primary(['product_id', 'attribute_id', 'devalue_id']);

});

Update 1

I need to set the sky, night

product_id  attribute_id      value       devalue_id
1           1                 sky         1
1           1                 night       2
...
+4
source share
2 answers

For something like this, I see 2 options:

1.

Manually add and separate the entries you want. This can lead to problems with the way you retrieve the data, although since it will return several identical attributes, you could use it groupByin the collection to get around this problem (if it is one for you).

2.

JSON . . AttributeProductPivot ( , ), Illuminate\Database\Eloquent\Relations\Pivot casts i.e.:

class AttributeProductPivot extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'value' => 'collection', //or object or array
    ];

}

attributes() :

public function attributes()
{
    return $this->belongsToMany(Attribute::class)
        ->using(AttributeProductPivot::class)
        ->withPivot('value');
}

using() Pivot- . , .

value json /.

, !

+2

100%, , .

1: . , . :

$product->attributes()->saveMany([
   new App\Attribute(['title' => 'sky']),
   new App\Attribute(['title' => 'night']),
]);

2: . . , , .

$attribute1 = Attributes::where('title', 'sky')->first();
$attribute2 = Attributes::where('title', 'night')->first();

$product->attributes()->saveMany([
    $attribute1,
    $attribute2,
]);
+1

Source: https://habr.com/ru/post/1680406/


All Articles