我使自己成为一个插件用于加载与beforeFind()
相关的内容,所以你可以说ContentPage/10
类似于ConentNews/10
和Gallery/5
。CakePHP 3.1,通用属于许多
我的表related_contents样子:
id int(11)
source_table_name varchar(255)
target_table_name varchar(255)
source_table_id int(11)
target_table_id int(11)
我的行为的代码:
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) {
$attachedTables = self::getAttachedTables(); //Array of ORM models which has this behavior
foreach ($attachedTables as $attachedTable) {
$options = [
'through' => 'RelatedContents',
'bindingKey' => 'RelatedContents.source_table_id',
'foreignKey' => 'RelatedContents.target_table_id',
'conditions' => [
'RelatedContents.source_table_name' => $this->_table->table(),
'target_table_name' => $attachedTable->table(),
]
];
$this->_table->belongsToMany($attachedTable->alias(), $options);
}
}
现在,当我在我的模型试图find()
,零个相关的实体,没有发现错误。我究竟做错了什么?
我不认为'beforeFilter'是放置代码的正确位置。试试'initialize'而不是 – arilia
我试过了,它会因getAttachedTables()方法触发递归。但我不认为它应该有所作为,我试图把hasMany放在查找之前,它的工作原理。 – Aiphee