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

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

问题描述

定义复合主键然后在实例模型上调用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行

$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类中创建新记录的代码.

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自动递增主键列,并为username添加唯一索引,和activity_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雄辩地无法使用复合主键保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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