I have products model that has many to many relationship with attributes and attributes_values
when i make changes to attribute values:
foreach ($attribute_list as $key => $value) {
...
$attribute = ProductsAttributes::where('code', '=', $key)->first();
$attr_values = $attribute->values()->updateOrCreate(
['id' => $value_id],
$value
);
$old_product_attributes = $old_product_attributes->merge([$key => $value_id]);
...
}
I would like to check if any column has been updated but if I
dd($attr_values->isDirty());
it returns false. but 1 column was changed during the update.
Currently the way i was checking for change was with sync:
$syncResult = $product->attr_values()->sync($old_product_attributes);
if (collect($syncResult)->flatten()->isNotEmpty()) {
$product->updated_at = now();
}
But also here if I dd($syncResult) it returns empty as no changes were made If i check products_atr_values table the column that had changes has updated updated_at.
What am i doing wrong?
Relationships:
Products model has:
public function attr_values()
{
return $this->belongsToMany('Modules\Products\Entities\ProductsAttributesValues', 'products_attributes_values_prod', 'product_id', 'value_id');
}
ProductsAttributes model has:
public function values()
{
return $this->hasMany('Modules\Products\Entities\ProductsAttributesValues', 'attribute_id');
}
ProductsAttributesValues model has:
public function attributes()
{
return $this->belongsTo('Modules\Products\Entities\ProductsAttributes');
}
public function products()
{
return $this->belongsToMany('Modules\Products\Entities\Products', 'products_attributes_values_prod', 'value_id', 'product_id');
}
public function attr_val_prod()
{
return $this->belongsToMany('Modules\Products\Entities\ProductsAttributesValuesProd', 'value_id');
}
isDirty()
is not working because is used when the model attribute is changed, but not yet saved in the database.
What you can do is if you only need to change product the updated_at field in your ProductsAttribuesValues model use:
protected $touches = ['products'];
or if you need to change more things you can use the saved event again in ProductsAttribuesValues:
protected static function booted()
{
static::saved(function ($model) {
$model->products()->update(['value' => $value]);
});
}