Suppose we have an Attribute
model that can have some Option
s.
On creating an attribute, we can specify some options for that. in fact there is a one to many relation between them.
Attribute
model is :
class Attribute extends Model
{
use \Dimsav\Translatable\Translatable;
protected $primaryKey = 'attribute_id';
public $translatedAttributes = ['title'];
protected $fillable = ['name', 'creator', 'type'];
public function options()
{
return $this->hasMany(AttributeOption::class, 'attribute_id', 'attribute_id');
}
}
And Option
model is like this :
class AttributeOption extends Model
{
use \Dimsav\Translatable\Translatable;
protected $fillable = ['attribute_id'];
public $translatedAttributes = ['title'];
public $timestamps = FALSE;
protected $primaryKey = 'attribute_option_id';
public function attribute()
{
return $this->belongsTo(Attribute::class, 'attribute_id', 'attribute_id');
}
}
For save an attribute with it's options I wrote this :
\DB::transaction(function () use ($attributeGroup, $request) {
$newAttribute = $attributeGroup->attributes()->create($request->all());
if ($request->has('type') && $request->get('type') == 'select') {
if ($request->has('options') and count($request->get('options')) > 0) {
$options = $request->get('options');
foreach ($options as $opt) {
$newAttribute->options()->create($opt);
}
}
}
return $this->item($newAttribute, new AttributeTransformer());
});
But now consider when a user want to update an attribute that in this case , may want to delete some options and add new ones.
And in this case I do not know how handle options. beacause I do not know how to recognize options that are removed that I can remove them from DB. and how can I update properties of options that does not touched and just fields like title
,desc
, ... are changed.