定义复合主键然后在实例化模型上调用save时,会抛出异常。
ErrorException (E_UNKNOWN)
PDO::lastInsertId() expects parameter 1 to be string, array given
错误发生在第32行
$id = $query->getConnection()->getPdo()->lastInsertId($sequence);
这里是Model
的声明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;
}
这是在Controller类中创建新记录的代码。
$attendance = new ActivityAttendance;
$attendance->activity_id = $activityId;
$attendance->username = $username;
$attendance->save();
答案 0 :(得分:0)
我假设这是一个数据透视表,在这种情况下,您不应该直接使用数据透视表。使用Activity
上的方法使用Attendance
或belongsToMany()
模型更新数据透视表,sync()
,attach()
,detach()
等...
如果出于某种原因无法实现,因为您的数据透视表还包含其他地方的密钥,则应删除当前主键,添加id
自动增量主键列并为{{添加唯一索引1}}和username
。
你也可以像这样保存它......可能值得一试。
activity_id
答案 1 :(得分:0)
您只能对模型的可填充属性中列出的属性使用:: create()。
class ActivityAttendance extends Model {
...
protected $fillable = ['activity_id', 'username'];
...
}
答案 2 :(得分:0)
在简单的情况下,人们也可能面临同样的错误。因此,在模型中创建复合主键时,还需要在模型定义中覆盖$ incrementing属性。如果没有声明你也会得到完全相同的错误,即[ErrorException'带消息'PDO :: lastInsertId()期望参数1为字符串]。
原因也许Eloquent尝试获取上一个自动编号的值。但是,Laravel没有完全支持复合键,我们大多数都必须使用查询生成器方法。
class ActivityAttendance extends Eloquent {
...
protected $incrementing = false;
...
}