Laravel中一对多关联关系更新实现(Attribute与Option场景)
嘿,我帮你把这段Laravel的Attribute模型代码规范格式化,顺便把关联关系的细节理清楚:
Attribute 模型实现(含与AttributeOption的一对多关联)
这是一个支持多语言翻译的Laravel Eloquent模型,核心是和AttributeOption建立一对多的关联关系——一个Attribute可以对应多个Option。
完整格式化后的模型代码
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'); } }
关键细节说明
- 多语言翻译支持:引入了
Dimsav\Translatable\Translatabletrait,通过$translatedAttributes指定title字段需要做多语言存储。 - 自定义主键:将模型主键设为
attribute_id,替代Laravel默认的id字段。 - 批量赋值白名单:
$fillable数组列出了允许通过create()、update()等批量赋值方法修改的字段:name、creator、type。 - 一对多关联:
options()方法通过hasMany定义关联,参数分别是:- 关联的模型类
AttributeOption::class - 关联模型(AttributeOption)中的外键
attribute_id - 当前模型(Attribute)的主键
attribute_id(原代码未补全,这里帮你补充完整)
- 关联的模型类
内容的提问来源于stack exchange,提问作者Ahmad Badpey
相关产品推荐
相关产品推荐

