cakephp 关联/取消关联(新)实体上的相关实体

1hdlvixo  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(224)

在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]);

那看起来不太优雅吧?

shyt4zoc

shyt4zoc1#

在CakePHP中没有与之等效的速记方法。
虽然belongsToManyhasMany关联具有**link()unlink()方法**来关联和保存实体,但belongsTohasOne没有类似的方法。
因此,现在您必须手动在正确的属性上设置实体,然后保存源实体,例如:

$entity = $this->Table->newEmptyEntity(); // or $this->Table->get(1); to update
$entity->set('related', $this->Related->get(1));
$this->Table->save($entity);

保存后,源实体将保存新关联记录的外键。如果您实际上不想保存它(无论出于何种原因),则您别无选择,只能手动设置实体上的外键,或者实现您自己的帮助器方法(该方法可识别关联配置),以便它知道要填充哪些属性。
首先,在基于\Cake\ORM\Association\BelongsTo的自定义关联类中,可能如下所示:

public function associate(EntityInterface $source, EntityInterface $target)
{
    $source->set($this->getProperty(), $target);

    $foreignKeys = (array)$this->getForeignKey();
    $bindingKeys = (array)$this->getBindingKey();
    foreach ($foreignKeys as $index => $foreignKey) {
        $source->set($foreignKey, $target->get($bindingKeys[$index]));
    }
}

然后可以像这样使用:

$entity = $this->Table->newEmptyEntity();
$this->Table->Related->associate($entity, $this->Related->get(1));

相关问题