Laravel + 可为空的外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23450953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:28:17  来源:igfitidea点击:

Laravel + nullable foreign keys

laravel

提问by mpen

I've got a form with a dropdown selection that lets you choose a foreign key for a particular model. The top option is always something like

我有一个带有下拉选项的表单,可让您为特定模型选择外键。最上面的选项总是像

<option value="">please select</option>

So when I fill my model with this data from the form,

所以当我用表单中的数据填充我的模型时,

$booking = new Booking($data);

And try to save it,

并尝试保存它,

$booking->save();

It always fails because that violates the FK constraint because Laravel isn't smart enough to nullify this field for me. Thus I came up with this little hack:

它总是失败,因为这违反了 FK 约束,因为 Laravel 不够聪明,无法为我取消这个字段。因此我想出了这个小技巧:

public function save() {
    if(!$this->vehicle_id) $this->vehicle_id = null;
    if(!$this->driver_id) $this->driver_id = null;
    parent::save();
}

But is there no way to tell Laravel which fields represent FKs and should be set to null if they an integer > 0?

但是有没有办法告诉 Laravel 哪些字段代表 FK,如果它们的整数 > 0 应该设置为 null?

回答by mpen

One possible solution is to use set mutatorsfor all your foreign keys:

一种可能的解决方案是对所有外键使用set mutators

public function setVehicleIdAttribute($value) {
    $this->attributes['vehicle_id'] = $value ?: null;
}

public function setDriverIdAttribute($value) {
    $this->attributes['driver_id'] = $value ?: null;
}