假设我们的Attribute
模型可以有一些Option
s。
在创建属性时,我们可以为其指定一些选项。事实上,它们之间存在一对多的关系。
Attribute
模型是:
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');
}
}
Option
模型是这样的:
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');
}
}
为了保存带有它的选项的属性,我写了这个:
\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());
});
但是现在考虑当用户想要更新属性时,在这种情况下,可能想要删除一些选项并添加新选项。
在这种情况下,我不知道如何处理选项。因为我不知道如何识别被删除的选项,我可以从DB中删除它们。以及如何更新未触及的选项的属性,只更改title
,desc
,...等字段。
答案 0 :(得分:0)
如果我理解正确,您的问题依赖于如何根据您当前的结构启用/禁用选项?在这种情况下,您可能需要表中另一个表示活动和非活动的值,您也可以使用软删除,但如果您计划定期激活和停用这些选项,则可能只是有点过分。在最后一个,如果您只是更改选项中的值,您将需要找到一种方法来确定用户正在修改的选项。通过从视图中传递选项的id来知道他正在修改的选项或其他方法,如果您可以确定该选项,您只需:
$option->{value-to-be-changed} = {value};
$option->save();
答案 1 :(得分:0)
$newAttribute->options()->sync([array of id's])
,但这适用于多对多。 sync
的作用是删除未包含在id数组中的关系。
可能对您有帮助的参考问题: