【发布时间】:2017-07-28 19:35:09
【问题描述】:
我使用的是 CakePHP 3.x 版。
我需要通过一个模型(TrackersArticlesMentions)链接三个模型(Trackers、Articles、Mentions) .
这是我的关系定义:
TrackersTable.php
$this->belongsToMany('Mentions', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Articles', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
ArticlesTable.php
$this->belongsToMany('Mentions', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Trackers', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
MentionsTable.php
$this->belongsToMany('Articles', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Trackers', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
TrackersArticlesMentionsTable.php
$this->belongsTo('Trackers', [
'foreignKey' => 'tracker_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Mentions', [
'foreignKey' => 'mention_id',
'joinType' => 'INNER'
]);
到目前为止,当我想找到我的数据并包含(也称为包含)它们时,一切都运行良好。
不幸的是,当我想链接它们时,我应该能够使用函数链接并执行以下操作:
$this->Trackers->link($trackerEntity, [$articleEntity, $mentionEntity]);
但它不起作用,函数 link 期望作为第二个参数:
属于该关联
target方的实体列表
我可能是错的,但函数似乎只链接两个实体,第二个参数只是同一实体的数组...
我通过在 TrackersArticlesMentionsTable 中创建一个函数找到了解决方案,如下所示:
public function createLink(\App\Model\Entity\Tracker $trackerEntity, \App\Model\Entity\Article $articleEntity, \App\Model\Entity\Mention $mentionEntity)
{
return $this->findOrCreate([
'tracker_id' => $trackerEntity->get('id'),
'article_id' => $articleEntity->get('id'),
'mention_id' => $mentionEntity->get('id'),
]);
}
但我想“正确”地做到这一点。 有人有什么建议吗? 谢谢!
【问题讨论】:
标签: php cakephp cakephp-3.0 entity-relationship model-associations