考虑到一些模型尝试使用 Contact::sync(array(1,2,3)) 添加邮件列表失败,因为主键 email_address 未填写。
表结构:
Contacts
- email_address string (PK)
- name string
MailingLists
- id integer (PK)
- name string
ContactMailingLists
- contact_id string (PK, FK)
- mailing_list_id integer (PK, FK)
和型号:
<?php
class MailingList extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'mailing_lists';
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function contacts ()
{
return $this->belongsToMany('\Application\Entity\Contact', null, 'id', 'email_address')->withTimestamps();
}
}
class Contact extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contacts';
/**
* @var string
*/
protected $primaryKey = 'email_address';
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function mailing_lists ()
{
return $this->belongsToMany('\Application\Entity\MailingList', null, 'id', 'mailing_list_id')->withTimestamps();
}
}
当在 eloquent 中使用 ->sync() 或其他关系函数时,它会产生错误。 sync() 方法会产生错误,因为在插入时 email_address 设置为 0 而不是 email_address。
编辑:将相关键添加到代码中。
最佳答案
将模型设置为不再尝试自动递增主键。
将其添加到任何没有自动递增键(例如 email_address)的模型上。
public $incrementing = false;
关于php - 具有基于字符串的主键的多对多 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708269/