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.