Laravel Eloquent cannot save models with composite primary keys

When defining composite primary keys, then calling store in the instance model, an exception is thrown.

ErrorException (E_UNKNOWN) 
PDO::lastInsertId() expects parameter 1 to be string, array given

      

An error occurred on line 32

$id = $query->getConnection()->getPdo()->lastInsertId($sequence);

      

And here is the model declaration

class ActivityAttendance extends Eloquent {
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'activity_attendance';

    /**
     * The primary key of the table.
     * 
     * @var string
     */
    protected $primaryKey = array('activity_id', 'username');

    /**
     * The attributes of the model.
     * 
     * @var array
     */
    protected $guarded = array('activity_id', 'username', 'guests');

    /**
     * Disabled the `update_at` field in this table.
     * 
     * @var boolean
     */
    public $timestamps = false;
}

      

Here is the code to create a new entry in the Controller class.

$attendance                 = new ActivityAttendance;
$attendance->activity_id    = $activityId;
$attendance->username       = $username;
$attendance->save();

      

+3


source to share


3 answers


I am assuming this is a pivot table, in which case you should not be working with the pivot table directly. Work with models Activity

or Attendance

using methods to belongsToMany()

, to update the PivotTable sync()

, attach()

, detach()

etc.

If for some reason this is not possible because your pivot table also contains keys going elsewhere, you should drop the current primary key, add the id

auto-increment primary key column, and add a unique index to username

, and activity_id

.



You might be able to keep it the same ... it might be worth taking a picture.

$attendance = ActivityAttendance::create(
    'activity_id' => $activityId,
    'username' => $username
);

      

0


source


You can use :: create () only the attributes listed in the attribute to populate the model.



class ActivityAttendance extends Model {
...
    protected $fillable = ['activity_id', 'username'];
...
}

      

0


source


In a simple script, you might also encounter the same error. Therefore, when creating a composite primary key in models, you also need to override the $ incrementing property in the model definition. If not declared, you will also get the same error. Ie [ErrorException "with message" PDO :: lastInsertId () expects parameter 1 to be a string].

Reason may be, the Eloquent is trying to get the value of the last auto-number. However, it is true that Laravel does not have full support for composite keys, and we are basically required to use the Query Builder approach.

class ActivityAttendance extends Eloquent {
   ...
   protected $incrementing = false;
   ...
}

      

0


source







All Articles