CakePHP实体包含没有外键 [英] CakePHP Entity contain without foreign key

查看:233
本文介绍了CakePHP实体包含没有外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体别墅,我希望这个实体包含具有相同复杂( Varchar(255))的别墅。 b
$ b

 类VillasTable扩展表
{
$ b $ / **
*初始化方法
*
* @param array $ config表的配置。
* @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']
]);
}
}
?>

我不知道这是否可能。我不想在每个需要这些实体的函数中添加一个查找。另外我想在使用这个新字段的实体中做一个函数。尽管事实上使用 VARCHAR(255) $`解决方案
``解决方案 c $ c>作为一个外键可能是非常低效的和/或将需要巨大的索引,我猜一般来说,定义另一个表的外键的选项将在这里派上用场,类似于 targetForeignKey 用于 belongsToMany 关联。您可能希望 建议将其作为增强功能



结果格式化程序



目前这似乎不可能使用关联开箱即可,所以你可能必须自己选择并注入相关的记录,例如在一个结果格式化程序中。

  $ Villas 
- > ()
- > formatResults(function b
$ b //从结果中提取自定义外键$ b $ key = array_unique($ results-> extract('complex') - > toArray());

//使用提取的外键找到关联的行
$ villas = \Cake\ORM\TableRegistry :: get('Villas')
- > find()
- > where(['' complex IN'=> $ keys])
- > all();

//将相关记录注入结果
return $ results-> map(function($ row)use($ villas){
if(isset($ row ['complex'])){
//根据自定义外键
//过滤关联记录,并将它们添加到行/实体的属性
$ row ['complexs '] = $ villas-> filter(function($ value,$ key)use($ row){
return
$ value ['complex'] === $ row ['complex']] &&
$ value ['id']!== $ row ['id'];
})
- > toArray(false);
}
返回$ row;
});
});

这将使用自定义外键获取关联的行,并注入结果,最终会得到相关的实体记录。



另见 食谱>数据库访问& ORM>查询生成器>添加计算字段



可能还有其他选项,例如使用收集所需密钥的自定义加载器,结合自定义关联类,使用正确的键将结果拼接在一起,请参阅


I have an entity Villa, and I want this Entity to contain other Villas which have the same 'complex' (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']
        ]);
    }
}
?>

I don't know if it's possible. I don't want to add a find in each function who need those entity. Also I would like to make a function in the Entity which uses this new field. ``

解决方案

Despite the fact that using a VARCHAR(255) as a foreign key is probably highly inefficient and/or will require huge indices, I guess that generally an option that defines the foreign key of the other table would come in handy here, similar to targetForeignKey for belongsToMany associations. You may to want to suggest that as an enhancement.

Result formatters

Currently this doesn't seem to be possible out of the box using associations, so you'd probably have to select and inject the associated records yourself, for example in a result formatter.

$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;
        });
    });

This would fetch the associated rows afterwards using the custom foreign keys, and inject the results, so that you'd end up with the associated records on the entities.

See also Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields

There might be other options, like for example using a custom eager loader that collects the necessary keys, combined with a custom association class that uses the proper key for stitching the results together, see

这篇关于CakePHP实体包含没有外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆