Laravel模型使用附加功能的多对多模型

时间:2015-11-10 20:11:24

标签: php database laravel eloquent

我想使用Laravel提供的模型附加功能向我的数据透视表添加信息。

模型包括此功能:

public function incidentTypes() {
    return $this->belongsToMany('App\IncidentType', 'incident_incident_type', 'incident_id', 'incident_type_id');
}

创建了数据透视表,它由两个FK组成。一个与表incidents相关,另一个与表incident_types

相关

当我使用修补程序测试设置时,我使用此函数调用:

$incident->incidentTypes()->attach('I100');

数据透视表

public function up()
    {
        Schema::create('incident_incident_type', function (Blueprint $table) {
            $table->string('incident_id')->index();
            $table->foreign('incident_id')->references('incident_id')->on('incidents');

            $table->string('incident_type_id')->index();
            $table->foreign('incident_type_id')->references('incident_type_id')->on('incident_types');
        });
    }

事件类

class Incident extends Model {

    use EventGenerator;

    protected $table = 'incidents';
    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', 'incident_type_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;
    }
}

IncidentType类

class IncidentType extends Model {

    protected $fillable = ['incident_id', 'incident_type_id'];

    public function incidents() {
        return $this->belongsToMany('App\Classes\Incident', 'incident_incident_type', 'incident_id', 'incident_type_id');
    }
}

错误

Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`homestead`.`incident_incident_type`, CONSTRAINT `incident_incident_type_incident_id_foreign` FOREIGN KEY (`incident_id`) REFERENCES `incidents` (`incident_id`)) (SQL: insert into `incident_incident_type` (`incident_id`, `incident_type_id`) values (0, AED))'

1 个答案:

答案 0 :(得分:0)

尝试使用create()方法获取已保存模型的实例,然后使用该模型附加您的incidentType。例如:

$incident = Incident::create(['property_name'=>'property_value']);
$incident->incidentTypes()->attach('I100');

否则,执行save()后,检索已保存的模型,然后附加您的incidentType。