efjot
June 3, 2025, 5:04pm
1
I saw several threads here with the same question but no one helped me.
I try to save data in an object with jointable.
First object is a worker
And the worker has many PLZ
$this->belongsToMany('PLZ', [
'foreignKey' => 'worker_id',
'targetForeignKey' => 'plz_id',
'joinTable' => 'workers_plz',
'dependent' => true
]);
There is a table plzTable wich contains plz_id and plz_no
When I try to create a worker, I will search for the plz_id in the plzTable.
This works fine.
But when I try to fill in the plz_id in the worker object, I receive an error.
worker->PLZ->id = $plz->id;
Errormessage:
Attempt to assign property “id” on null
But the worker object is not null and when I check the accessibility the the PLZ is true.
I am really not sure how cakephp saves data in a join table.
Maybe someone can help
I recommend to stop using non-conventional naming. This will only get you in trouble, and likely already has.
$this->belongsToMany(‘CamelCaseNaming’, […]
etc
Also, never directly assign the primary keys, never needed in these cases.
Create workers using the documented newEntity() etc.
Or did you want to assign this to a foreign key? $worker->pivot_table->plz_id = .. ?
efjot
July 11, 2025, 8:06pm
3
Hi, sorry for not answering that long time.
I changed my code:
$this->belongsToMany('WorkersPlz', [
'foreignKey' => 'worker_id',
'targetForeignKey' => 'plz_id',
'joinTable' => 'workers_plz',
'dependent' => true
]);
I created a new WorkersPlzTable class as well.
But now I get the errormessage:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'WorkersPlz'
and the class looks like this:
class WorkersPlzTable extends Table
{
/**
* Initialize method
*
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('plz');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsToMany('Workers', [
'foreignKey' => 'plz_id',
'targetForeignKey' => 'worker_id',
'joinTable' => 'workers_plz',
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->integer('plz_no')
->requirePresence('plz_no', 'create')
->notEmptyString('plz_no');
$validator
->scalar('plz_city')
->maxLength('plz_city', 255)
->allowEmptyString('plz_city');
$validator
->scalar('land_name')
->maxLength('land_name', 255)
->allowEmptyString('land_name');
return $validator;
}
}
Not sure what is the problem right now
Use 'plzs' => [['id' => $plz->id]]
when creating or patching the worker. Avoid assigning $worker->PLZ->id
directly—it’s null until initialized.