具有两个hasOne关系的模型与同一张表 [英] Models with two hasOne relations to same table
问题描述
我正在用CakePHP建立一个MMA(综合武术)网站。我的数据库中有一个 fights
表,其中最简单的是三列: id
, fighter_a
和 fighter_b
。
I'm building an MMA (mixed martial arts) website with CakePHP. I've got a fights
table in my database that has three columns at its simplest: id
, fighter_a
, and fighter_b
.
我遇到麻烦了我的 Fight
模型与我的 Fighter
模块将具有哪种关系。我是否认为 fighter_a
和 fighter_b
是两个 hasOne
关系?
I'm having trouble getting my head around what type of relation my Fight
model would have with my Fighter
module. Am I right in thinking fighter_a
and fighter_b
would be two hasOne
relations?
我在战斗
模型中尝试了以下方法:
I tried this with the following in my Fight
model:
<?php
class Fight extends AppModel {
public $name = 'Fight';
public $hasOne = array(
'FighterA' => array(
'className' => 'Fighter',
'foreignKey' => 'fighter_a'
),
'FighterB' => array(
'className' => 'Fighter',
'foreignKey' => 'fighter_b'
)
);
}
然后在我的 Fighter
模型:
<?php
class Fighter extends AppModel {
public $name = 'Fighter';
public $hasMany = array(
'Fight'
);
}
但这在我的CakePHP应用程序中调用 $ this-> Fight-> findById($ id)
(其中 $ id
是战斗机的ID):
But this threw an error in my CakePHP application when calling $this->Fight->findById($id)
(where $id
was the ID of a fighter):
错误: SQLSTATE [42S22]:找不到列:1054字段列表中的未知列 Fight.fighter_id
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Fight.fighter_id' in 'field list'
如何链接我的模型,以便可以调用战斗机参加的所有战斗?
How can I link my models so that I can call all fights a fighter has been in?
推荐答案
从问题中的对话中提炼出来的解决方案是:
Distilled from conversation under the question, the solution would be this:
将$ hasMany重写为您的FighterModel如下所示:
Rewrite the $hasMany in your FighterModel to look like:
public $hasMany = array(
'Fight' => array(
'className' => 'Fight',
'finderQuery' => 'SELECT * FROM fights AS Fight WHERE Fight.fighter_a_id = {$__cakeID__$} OR Fight.fighter_b_id = {$__cakeID__$};'
)
);
这篇关于具有两个hasOne关系的模型与同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!