Models with two hasOne relations to same table

半世苍凉 提交于 2019-12-24 03:34:21

问题


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.

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

And then this in my Fighter model:

<?php
class Fighter extends AppModel {

    public $name = 'Fighter';
    public $hasMany = array(
        'Fight'
    );
}

But this threw an error in my CakePHP application when calling $this->Fight->findById($id) (where $id was the ID of a fighter):

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?


回答1:


Distilled from conversation under the question, the solution would be this:

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


来源:https://stackoverflow.com/questions/8962904/models-with-two-hasone-relations-to-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!