简体   繁体   中英

Custom Primary Key in laravel

I created a class:

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;
    }
}

The primary key should be a custom one incident_id . Thats why I set the property. Still when I use tinker to create an object like this:

$incident = new \App\Incident
$incident->incident_id = "I100"
$incident->save()
$incident->incidentTypes()->attach("AED")

and want to use the attach() method, I get the error:

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))'

Question

Why is the value being added to the SQL statement still "0" and not "I100" like I added it? as this is the valid PK and not 0 (which would be the default "id" field as a PK.

If you have confirmed that the initial $incident->save() is working correctly by saving the correct data to your database, try a dd() immediately after to see the current state of $incident:

dd($incident->incident_id);

Based on what you're reporting, this value should output as '0' or null. If that's the case, try:

$incident = $incident->save();

Repeat the dd(), and hopefully you'll see the correct value.

If, in fact, your incident is not saving to the database correctly. You will need to try guard/reguard to make your primary key assignable:

$incident->unguard();
$incident->incident_id = "I100";
$incident->reguard();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM