我有一个实体别墅,我希望这个实体包含其他具有相同复杂性的别墅。 (Varchar(255)
)。
class VillasTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('villas');
$this->displayField('name');
$this->primaryKey('id');
$this->hasMany('Complexs', [
'className' => 'Villas',
'foreignKey' => false,
'propertyName' => 'complexs',
'conditions' => ['Complexs.complex' => 'Villas.complex']
]);
}
}
?>
我不知道是否可能。我不想在每个需要这些实体的功能中添加查找。另外,我想在使用这个新字段的Entity中创建一个函数。 ``
答案 0 :(得分:1)
尽管使用VARCHAR(255)
作为外键可能非常低效和/或需要大量索引,但我想通常一个定义另一个表的外键的选项在这里会派上用场,与targetForeignKey
关联的belongsToMany
类似。您可能需要 suggest that as an enhancement 。
目前,使用关联似乎无法开箱即用,因此您可能必须自己选择并注入相关记录,例如在结果格式化程序中。
$Villas
->find()
->formatResults(function($results) {
/* @var $results \Cake\Datasource\ResultSetInterface|\Cake\Collection\Collection */
// extract the custom foreign keys from the results
$keys = array_unique($results->extract('complex')->toArray());
// find the associated rows using the extracted foreign keys
$villas = \Cake\ORM\TableRegistry::get('Villas')
->find()
->where(['complex IN' => $keys])
->all();
// inject the associated records into the results
return $results->map(function ($row) use ($villas) {
if (isset($row['complex'])) {
// filters the associated records based on the custom foreign keys
// and adds them to a property on the row/entity
$row['complexs'] = $villas->filter(function ($value, $key) use ($row) {
return
$value['complex'] === $row['complex'] &&
$value['id'] !== $row['id'];
})
->toArray(false);
}
return $row;
});
});
这将使用自定义外键随后获取关联的行,并注入结果,以便您最终获得实体上的关联记录。
另请参阅 Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields
可能还有其他选项,例如使用收集必要键的自定义eager加载器,结合使用正确键将结果拼接在一起的自定义关联类,请参阅