Given a few models trying to use Contact::sync(array(1,2,3)) to add mailing lists fails because the primary key email_address does not get filled out.
The table structure:
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)
And Models:
<?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();
}
}
When using ->sync() or other relational functions in eloquent it produces errors. The sync() method produces an error because on the insert the email_address is set to 0 instead of the email_address.
EDIT: Added the related keys to the code.
You should pass the custom key
when declaring the relation along with the pivot table
name:
public function mailing_lists ()
{
return $this->belongsToMany('\Application\Entity\MailingList', 'ContactMailingLists', 'email_address', 'MailingList_id')
->withTimestamps();
}
Check the manual.
Set the models to no longer attempt to auto increment the primary key.
Add this on any models that don't have an auto incrementing key (such as email_address).
public $incrementing = false;