我为垒球队制作了一个小应用程序。我想建立以下关联:
模型Game
有两列away_id
,home_id
,这两列都是Team.id
的别名。
在Game
模型中我有:
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Home' => array(
'className' => 'Team',
'foreignKey' => 'home_id', // also tried simply 'id'
'conditions' => '',
'fields' => '',
'order' => ''
),
'Away' => array(
'className' => 'Team',
'foreignKey' => 'away_id', // also tried simply 'id'
'conditions' => '',
'fields' => '',
'order' => ''
)
);
在Team
模型中我有:
public $virtualFields = ['home_id' => 'Team.id', 'away_id' => 'Team.id'];
和
/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
'Game' => array(
'className' => 'Game',
'foreignKey' => 'home_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
// also tried only one 'Game' association with foreignKey => [home_id, away_id]
'Game' => array(
'className' => 'Game',
'foreignKey' => 'away_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
收到以下错误:
注意:" Psychouts"是下面SQL中唯一不可解释的外观;它是数据库名称(以及我的团队名称,henh)。
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Team.id' in 'field list'
SQL查询:SELECT Game
。id
,Game
。when
,Game
。cancelled
,Game
。{ {1}},field
。Game
,home_id
。Game
,away_id
。Game
,score_us
。{{1 },Game
。score_them
,Home
。id
,Home
。captain_id
,Home
。name
,Home
。wins
,Home
。losses
,Home
。ties
,Home
。scored
,( Home
。allowed
)AS Team
,(id
。Home__home_id
)AS Team
,id
。Home__away_id
,Away
。id
,Away
。captain_id
,Away
。name
,Away
。wins
,{ {1}}。Away
,losses
。Away
,ties
。Away
,(scored
。Away
)AS { {1}},(allowed
。Team
)AS id
FROM Away__home_id
。Team
AS id
LEFT JOIN Away__away_id
。 psychouts
AS games
ON(Game
。psychouts
= teams
。Home
)LEFT JOIN Game
。home_id
AS Home
ON(id
。psychouts
= teams
。Away
)WHERE 1 = 1 LIMIT 20
答案 0 :(得分:0)
根据AD7six的评论,经过测试,似乎正确的解决方案是:
在Team
模型中,删除我建议的虚拟字段,然后按如下方式定义Game
关联:
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Game' => array(
'className' => 'Game',
'foreignKey' => ['OR' => ['Game.home_id = Team.id', 'Game.away_id = Team.id']]
'conditions' => '',
'fields' => '',
'order' => ''
),
);
在Game
模型中,像往常一样定义Team
关联:
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Team' => array(
'className' => 'Team',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);