Laravel Eloquent 无法使用复合主键保存模型 [英] Laravel Eloquent CANNOT Save Models with Composite Primary Keys

查看:34
本文介绍了Laravel Eloquent 无法使用复合主键保存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义复合主键然后在实例化模型上调用 save 时,会引发异常.

When defining composite primary keys then calling save on an instanced model, an exception is thrown.

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

错误发生在第 32 行

The error occurred at line 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;
}

这是在 Controller 类中创建新记录的代码.

Here's the code to create new record in Controller class.

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

推荐答案

我假设这是一个数据透视表,在这种情况下您不应该直接使用数据透视表.使用 belongsToMany() 上的方法处理 ActivityAttendance 模型以更新数据透视表 sync()attach()detach() 等...

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...

如果由于某些原因不可能,因为您的数据透视表还包含其他地方的键,您应该删除当前的主键,添加一个 id 自动递增的主键列并添加一个唯一索引到 usernameactivity_id.

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

这篇关于Laravel Eloquent 无法使用复合主键保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆