Laravel Eloquent CANNOT Save Models with Composite Primary Keys

爷,独闯天下 提交于 2019-12-01 20:38:31

I'm assuming this is a pivot table, in which case you shouldn't be working with the pivot table directly. Work with either the Activity or Attendance models using the methods on belongsToMany() to update the pivot table, sync(), attach(), detach(), etc...

If for some reason that is not possible because your pivot table also contains keys going elsewhere, you should remove the current primary key, add an id auto-increment primary key column and add a unique index to username, and activity_id.

You may be able to save it like this as well... might be worth a shot.

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

You can only use ::create() on attributes you listed in your model's fillable attribute.

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

In simple scenario one may also face same error. So when creating composite primary key in models you also need to override $incrementing property in your model definition. If not declared you'll also get exact same error i.e [ErrorException' with message 'PDO::lastInsertId() expects parameter 1 to be string].

Reason maybe Eloquent try to get value of last auto-number. However its true that Laravel don't have full support of composite keys and we are mostly bound to use Query Builder approach.

class ActivityAttendance extends Eloquent {
   ...
   protected $incrementing = false;
   ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!