I'm experiencing an odd behaviour when working with models with many-to-many relations.
Here's a mock of my Models:
class Job{
public $id;
public $name;
public function initialize(){
$this->hasMany('id', 'JobBenefit', 'job_id', ['alias'=>'jobBenefits']);
$this->hasManyToMany('id', 'JobBenefit', 'job_id', 'benefit_id', 'Benefit', 'id', ['alias'=>'benefits']);
}
}
class Benefit{
public $id;
public function initialize(){
$this->hasMany('id', 'JobBenefit', 'benefit_id', ['alias'=>'jobBenefits']);
}
}
class JobBenefit{
public $job_id;
public $benefit_id;
public function initialize(){
$this->belongsTo('job_id', 'Job', 'id');
$this->belongsTo('benefit_id', 'Benefit', 'id');
}
}
And here's whats happening:
//This works:
$job = Job::findFirstById(1);
$job->name = 'Hi there';
$job->update(); //OK
$job->name = 'Something new';
//[... some more changes ...]
$job->update(); //OK
//This DOESN'T
$benefits = Benefits::find(['id > 10']);
$job = Job::findFirstById(1);
$job->name = 'Hi there';
$job->jobBenefits->delete(); //OK, removes the relation between this job and all hits benefits
$job->benefits = $benefits;
$job->update(); //OK, the new relations [JobBenefit] are saved on the database
$job->name = 'Something new';
//[... some more changes ...]
$job->update(); //ERROR. PDOException: duplicate entry for key job_id_benefit_id
I've checked the dirty state of the job, the benefits and the relations (jobbenefit), and all of them are 0
So, my question is: Why is it trying to save the relations again?