I have this model and controller and it returns fine if it is a hasOne relationship but now DishCategory hasMany dishes. When I change the code below to hasMany it gives me an error saying Dish.id is not a known column while if it is a hasOne it works fine. How can I make it so that it returns all the Dish.id’s that have id=1? (still using the join).
class DishCategory extends AppModel{
public $hasOne = array(
'Dish' => array(
'className' => 'Dish',
'foreignKey' => 'dish_category_id'
)
);
}
class DishCategoriesController extends AppController {
function get_categories($id)
{
// find category with a dish of $id
$this->set('dishes', $this->DishCategory->find('all', array(
'conditions' => array(
'Dish.id' => $id
)
)));
// set master layout
$this->layout = 'master_layout';
}
}
hasOnerelations can be joined into the primary SQL query.hasManyrelations cannot and need to be queried in a separate query. Theconditionsyou specify for the query only apply to the primary query, all separate relational queries are build just based on theids retrieved in the primary query. Set debug to 2 and have a good look at the query log to see what I mean.To find the category of a dish, fetch the dish and look at its related category record:
Since I take it that a dish
belongsToone category, your query “find all categories which have a dish with id x” makes little sense; there should only be one anyway.