在插入数据库时,我需要保护ID列,但是在插入其他数据库时,由于需要手动设置ID,因此我不想保护它,以便表同步。
但是我不知道该怎么做,下面是我目前所拥有的,但是这根本不起作用,因为我刚遇到一个错误:
字段“ id”没有默认值
这是我当前的模型:
<?php
namespace App\Models\Seasonal;
use Illuminate\Database\Eloquent\Model;
class SeasonalBanner extends Model
{
protected $connection = 'dev';
protected $guarded = [ 'id' ];
protected $appends = [ 'period' ];
public static function boot()
{
parent::boot();
self::creating(function($model){
if ($model->connection === 'live') {
$model->guarded = [];
}
});
}
public function dates() {
return $this->hasMany(SeasonalBannerDates::class);
}
public function getPeriodAttribute() {
return [ $this->start, $this->end ];
}
}
答案 0 :(得分:1)
我认为最好的方法是完全不使用$guarded
。刚刚设置:
protected $guarded = [];
,并根据您使用的数据库在代码中填充或不填充id
。