Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel Eloquent无法使用复合主键保存模型_Laravel_Eloquent_Composite Primary Key - Fatal编程技术网

Laravel Eloquent无法使用复合主键保存模型

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

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

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()无法工作。