我创建了一个类:
class Incident extends Model {
use EventGenerator;
protected $table = 'incidents';
protected $primaryKey = "incident_id";
protected $fillable = ['incident_id', 'incident_type', 'location', 'street', 'city', 'latitude', 'longitude', 'date', 'time', 'incident_archived'];
public $timestamps = true;
public function set($data) {
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
return $this;
}
public function responders() {
return $this->hasMany('App\Classes\Responder');
}
public function incidentTypes() {
return $this->belongsToMany('App\IncidentType', 'incident_incident_type', 'incident_id');
}
// set fields on the eloquent object and save to database
// raise event that the incident was created.
public function createIncident($command) {
$this->incident_id = $command->incidentId;
$this->save();
$this->raise(new IncidentWasPosted($this));
return $this;
}
}
主键应该是自定义键incident_id
。这就是为什么我设置属性。还是当我使用修补匠来创建这样的对象时:
$incident = new \App\Incident
$incident->incident_id = "I100"
$incident->save()
$incident->incidentTypes()->attach("AED")
并且想要使用attach()方法,我收到错误:
Illuminate \ Database \ QueryException,带有消息' SQLSTATE [23000]: 完整性约束违规:1452无法添加或更新子行: 外键约束失败(
homestead
。incident_incident_type
, 约束incident_incident_type_incident_id_foreign
外键 (incident_id
)REFERENCESincidents
(incident_id
))(SQL:insert 进入incident_incident_type
(incident_id
,incident_type_id
) 值(0,AED))'
问题
为什么要添加到SQL语句的值仍然是" 0"而不是" I100"就像我添加了它?因为这是有效的PK而不是0(这将是默认的" id"字段作为PK。
答案 0 :(得分:0)
如果您通过将正确的数据保存到数据库确认初始$ incident-> save()工作正常,请立即尝试使用dd()查看$ incident的当前状态:
dd($incident->incident_id);
根据您报告的内容,此值应输出为“0”或null。如果是这种情况,请尝试:
$incident = $incident->save();
重复dd(),希望你能看到正确的值。
事实上,如果您的事件不正确保存到数据库。您需要尝试使用guard / reguard来分配主键:
$incident->unguard();
$incident->incident_id = "I100";
$incident->reguard();