Note that there are some explanatory texts on larger screens.

plurals
  1. POFind fights for a fighter in CakePHP
    primarykey
    data
    text
    <p>I have two models: <code>Fight</code> and <code>Fighter</code>. My <code>Fight</code> model has two <code>belongsTo</code> relationships:</p> <pre><code>&lt;?php class Fight extends AppModel { public $belongsTo = array( 'FighterA' =&gt; array( 'className' =&gt; 'Fighter', 'joinTable' =&gt; 'fighters', 'foreignKey' =&gt; 'fighter_a_id' ), 'FighterB' =&gt; array( 'className' =&gt; 'Fighter', 'joinTable' =&gt; 'fighters', 'foreignKey' =&gt; 'fighter_b_id' ) ); } </code></pre> <p>This is so I can set two fighters that participate in a fight. However, I’m having difficulty working out how to set the other side of the relationship, in my <code>Fighter</code> model.</p> <p>I know I want to find all fights where either the <code>fighter_a_id</code> or <code>fighter_b_id</code> column equals the fighter ID, but having trouble translating this to a relationship in my model.</p> <p>I’ve tried:</p> <pre><code>&lt;?php class Fighter extends AppModel { public $hasMany = array( 'Fight' =&gt; array( 'conditions' =&gt; array( 'OR' =&gt; array( 'Fight.fighter_a_id' =&gt; 'Fighter.id', 'Fight.fighter_b_id' =&gt; 'Fighter.id' ) ) ) ); } </code></pre> <p>But CakePHP throws an error, where it is still trying to query the (non-existent) <code>fighter_id</code> it’s automatically generating, combining the generated <code>WHERE</code> clause with the <code>OR</code> clause I‘ve specified above.</p> <blockquote> <p>Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Fight.fighter_id' in 'field list'</p> </blockquote> <p>And the generated SQL statement:</p> <blockquote> <p><code>SELECT Fight.id, Fight.fighter_a_id, Fight.fighter_b_id, Fight.event_id, Fight.weight_division_id, Fight.rounds, Fight.rounds_length, Fight.winner, Fight.winning_round, Fight.winning_time, Fight.win_method, Fight.fighter_id FROM fights AS Fight WHERE ((Fight.fighter_a_id = 'Fighter.id') OR (Fight.fighter_b_id = 'Fighter.id')) AND Fight.fighter_id = (1)</code></p> </blockquote> <p>When finding records from the <code>fighters</code> table, I’d like to also list related <code>Fight</code> models (in chronological order, but that’s handled in another column left out as it’s unrelated to this issue).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload