You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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\Translatable trait,通过$translatedAttributes指定title字段需要做多语言存储。
  • 自定义主键:将模型主键设为attribute_id,替代Laravel默认的id字段。
  • 批量赋值白名单:$fillable数组列出了允许通过create()、update()等批量赋值方法修改的字段:name、creator、type。
  • 一对多关联:options()方法通过hasMany定义关联,参数分别是:
    1. 关联的模型类AttributeOption::class
    2. 关联模型(AttributeOption)中的外键attribute_id
    3. 当前模型(Attribute)的主键attribute_id(原代码未补全,这里帮你补充完整)

内容的提问来源于stack exchange,提问作者Ahmad Badpey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:53:34