在CakePHP4.x中是否有方法将一个实体与另一个实体关联/分离?类似于Laravel的方法?https://laravel.com/docs/8.x/eloquent-relationships#updating-belongs-to-relationships
例如,如果我创建一个新实体并分配一个相关实体,如下所示:
# in a controller
$entity = $this->Entity->newEmptyEntity();
$related = $this->Related->get(1);
$entity->set('related', $related);
这将把$related绑定到$entity->related
,但它不会设置$entity->relation_id = 1
。我怀疑$this->Entity->save($entity)
会设置$entity-〉relation_id,但我不想保存它。
一种解决方法是:
$entity->set(['related_id' => $related->id ,'related', $related]);
那看起来不太优雅吧?
1条答案
按热度按时间shyt4zoc1#
在CakePHP中没有与之等效的速记方法。
虽然
belongsToMany
和hasMany
关联具有**link()
和unlink()
方法**来关联和保存实体,但belongsTo
或hasOne
没有类似的方法。因此,现在您必须手动在正确的属性上设置实体,然后保存源实体,例如:
保存后,源实体将保存新关联记录的外键。如果您实际上不想保存它(无论出于何种原因),则您别无选择,只能手动设置实体上的外键,或者实现您自己的帮助器方法(该方法可识别关联配置),以便它知道要填充哪些属性。
首先,在基于
\Cake\ORM\Association\BelongsTo
的自定义关联类中,可能如下所示:然后可以像这样使用: