【问题标题】:Associate/Dissociate related entity on (new) entity在(新)实体上关联/分离相关实体
【发布时间】:2021-05-19 11:53:36
【问题描述】:

有没有办法在 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]);

看起来不是很优雅?

【问题讨论】:

  • 我对 Laravel 不太熟悉,但从文档来看,attach() 的工作方式并非如此,因为它似乎只适用于多对多关系,外键可以不存在于源端(因此没有键可以添加到源实体),它实际上将数据插入数据库,因此可能需要源已经持久化?!
  • 是的,你是对的,attach() 用于多对多关系。 BelongsTo 与 Associate/dissociate laravel.com/docs/8.x/… 合作,这也符合我的要求。我已经用关联/分离而不是附加/分离更新了问题。

标签: cakephp cakephp-4.x


【解决方案1】:

在 CakePHP 中没有等效的速记方法。

虽然belongsToManyhasMany 关联具有the link() and unlink() methods 来关联和保存实体,但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));

【讨论】:

  • 感谢您澄清这一点并提供可能的解决方案:-)
猜你喜欢
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多