Laravel Eloquent无法使用复合主键保存模型
定义复合主键,然后对实例模型调用save时,会引发异常Laravel Eloquent无法使用复合主键保存模型,laravel,eloquent,composite-primary-key,Laravel,Eloquent,Composite Primary Key,定义复合主键,然后对实例模型调用save时,会引发异常 ErrorException (E_UNKNOWN) PDO::lastInsertId() expects parameter 1 to be string, array given 错误发生在第32行 $id = $query->getConnection()->getPdo()->lastInsertId($sequence); 这是模型的声明 class ActivityAttendance extends
ErrorException (E_UNKNOWN)
PDO::lastInsertId() expects parameter 1 to be string, array given
错误发生在第32行
$id = $query->getConnection()->getPdo()->lastInsertId($sequence);
这是模型的声明
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;
}
下面是在控制器类中创建新记录的代码
$attendance = new ActivityAttendance;
$attendance->activity_id = $activityId;
$attendance->username = $username;
$attendance->save();
我假设这是一个透视表,在这种情况下,您不应该直接使用透视表。使用
下的方法更新透视表、同步()
、附加()
、分离()
等,使用活动
或考勤
模型
如果由于透视表还包含其他位置的键而无法执行此操作,则应删除当前主键,添加一个id
自动递增主键列,并向username
和activity\u id
添加唯一索引
你也可以这样保存它。。。也许值得一试
$attendance = ActivityAttendance::create(
'activity_id' => $activityId,
'username' => $username
);
只能对模型的可填充属性中列出的属性使用::create()
class ActivityAttendance extends Model {
...
protected $fillable = ['activity_id', 'username'];
...
}
在简单的情况下,一个人也可能面临同样的错误。因此,在模型中创建复合主键时,还需要覆盖模型定义中的$incrementing属性。如果未声明,您也将得到完全相同的错误,即消息“PDO::lastInsertId()期望参数1为字符串”的[ErrorException]
原因可能是雄辩地试图获得最后一个自动编号的值。然而,Laravel确实不完全支持复合键,我们通常使用查询生成器方法
class ActivityAttendance extends Eloquent {
...
protected $incrementing = false;
...
}
我使用的Laravel版本是4.2.11,这是迄今为止的最新版本。也许这是Laravel框架的一个缺陷?我想你已经一针见血了——Laravel无法处理复合主键。您可以定义它们,但一旦它需要为关系使用密钥,它就会失败。我听说没有ID列的数据透视表(即主数据透视表是由两个待数据透视的ID组成的复合键)通常是可以的,但这只是因为BelongToMany代码知道可能有两个列作为其内容的基础。尽管如此,我还是用一个主ID列定义了我的透视表,以确保它是正确的!我通过在模型之间使用belongtomany()
函数解决了这个问题。顺便说一句,由于未知原因,方法::create()无法工作。