我使用CakePHP 2.5.2并且在搜索数据方面遇到了一些麻烦。
在我的申请表中我有3张桌子,球队,球员,技能......团队中有80条记录,玩家2400条记录,技能2400条记录......我想计算一个团队的平均技能。 ..
//Team model
public $actsAs = array('Containable');
public $hasMany = array('Player');
//Player model
public $actsAs = array('Containable');
public $hasOne = array('Skill');
public $belongsTo = array('Team');
//Skill model
public $actsAs = array('Containable');
public $belongsTo = array('Player');
我的研究是:
$team = $this->Team->find('all', array(
'contain' => array(
'Player' => array(
'Skill'
)
),
));
$this->set('team', $team);
给出了预期的结果:
Array
(
[0] => Array
(
[Team] => Array
(
[id] => 1
[name] => my_team_name
)
[Player] => Array
(
[0] => Array
(
[id] => 000000419
[name] => Name
[surname] => Surname
[age] => 21
[team_id] => 1
[Team_id] => 1
[Skill] => Array
(
[id] => 20
[player_id] => 000000419
[skill] => 599
)
), ecc.....
此结构使用至少1680个查询...这对我来说太过分了......
我尝试了另一种方式,只涉及一个查询,返回错误的数据结构,但我需要的所有信息(也是多余的)。不幸的是,按照这种方式,我无法在View中迭代以显示我需要的内容。
$player = $this->Team->Player->find('all', array(
'contains' => array(
'Skill',
),
返回
Array
(
[0] => Array
(
[Player] => Array
(
[id] => 000000400
[nome] => my_player_name
[cognome] => my_player_surname
[nation_id] => 380
[age] => 29
[team_id] => 2
)
[Team] => Array
(
[id] => 2
[nome] => my_team_name
)
[Skill] => Array
(
[id] => 1
[player_id] => 000000400
[average] => 632
)
)
ecc.
有没有办法在VIEV中迭代以获得每支球队的平均技能?还有其他解决方案吗?
谢谢!
答案 0 :(得分:1)
如果可以将CakePHP升级到2.6或更高版本,则可以使用我的插件解决此问题。该插件与ContainableBehavior具有高度兼容性,但会生成更好的查询。 我认为find操作只会执行2个查询。 如果你尝试的话,我会很高兴的。
https://github.com/chinpei215/cakephp-eager-loader
<强>用法强>
<强> 1。启用EagerLoader插件
// In your model
$actsAs = ['EagerLoader.EagerLoader'];
如果你害怕加载我的插件会破坏某些地方,你也可以动态启用它。
// On the fly
$this->Team->Behaviors->load('EagerLoader.EagerLoader');
<强> 2。执行相同的查找操作
$this->Team->find('all', ['contain' => ['Player' => ['Skill']]]);
第3。查看查询日志
您将看到查询日志,如下所示:
SELECT ... FROM teams AS Team WHERE 1 = 1;
SELECT ... FROM players AS Player LEFT JOIN skills AS Skill ON Player.id = Skill.player_id WHERE Player.id IN ( ... );
答案 1 :(得分:-2)