Sorry if this is obvious – I’m trying to do a find() on a join table and failing, whats the correct syntax to do this?
Basically I have expenseCode table with a HABTM releationship with the expense table.
In my expenseCode model I have:
public function beforeDelete($cascade = false) {
$count = $this->Expense->find("count", array(
'conditions' => array('expense_code_id' => $this->id)
));
if ($count == 0) {
return true;
} else {
//$this->Session->setFlash('Record cannot be deleted as it has ' . $count . 'number of expenses attached to it');
return false;
}
}
If I uncomment the setFlash() I get the error.
Where am I going wrong? Thanks in advance.
Unfortunately it’s not possible to perform such a query on the HABTM join table from one of the parent models without some extra work. I’m assuming that Expense is the parent model and ExpensesCode the join model?
A common way is to modelise the HABTM join table. Say you have an
expensesandcodestable which are joined byexpenses_codes:However, Cake also auto-iniatlises a model for the join table when a HABTM association is defined (see the manual, and the “with” key in the list of possible keys).
So this syntax would let you directly query the join table:
The query above will net you with an array containing only the results from the join table, as it doesn’t perform a join like the first procedure. So you would have to perform a second
find()on the Expense model to find the expenses related to theexpense_code_idfrom ExpensesCode.EDIT:
It’s a framework convention that HABTM join tables should be underscored and alphabetically ordered. So if the HABTM join table is called
codes_expenses, it’s auto-modelised asCodesExpense.