I have three database tables:
-applicants
-language_skills
-applicants_language_skills
applicants_language_skills is the join table, which has some extra columns:
id | applicant_id | language_skill_id | read_level | write_level
these are set up like this:
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('language_skills');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsToMany('Applicants', [
'through' => 'ApplicantsLanguageSkills',
]);
}
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('applicants');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsToMany('LanguageSkills', [
'through' => 'ApplicantsLanguageSkills',
]);
}
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('applicants_language_skills');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Applicants');
$this->belongsTo('LanguageSkills');
}
I need some code examples on how to read, insert and update. I do not understand the documentation very good.
reading
This works:
$applicant = $this->Applicants->findBySlug($applicant_slug)
->contain([
'LanguageSkills',
])
->first();
I get an applicant entity which has an array of language_skills and in each language_skill is a value _joinData that contains read_level and write_level.
How should i update values of read_level and write_level in the joinTable.
I tried this, which works, but is this the correct way???
$current_readlevel = $applicant->language_skills[0]->_joinData->read_level;
$applicant->language_skills[0]->_joinData->read_level = 5;
$applicant->setDirty('language_skills', true);
$result = $this->Applicants->save($applicant, [
'associated' => ['LanguageSkills._joinData'],
]);
How can i add a new language skill for the applicant ?
$skill_klingon = $this->Applicants->LanguageSkills->get(5); // get a skill from the db
$skill_klingon->_joinData = new Entity(['read_level' => 3, 'markNew' => true]);
$applicant->language_skills[] = $skill_klingon;
$applicant->setDirty('language_skills', true);
$result = $this->Applicants->save($applicant);
This works, but if the $applicant already has a language_skill with id 5, it is not overwritten, i end up with two entries in the jointable for the applicant_id and language_skill_id 5.
The docs are not very helpful and searching google also does not really help. The docs also talk about link()
for example.
Hope somebody has some examples using this setup.