I’m currently using CakePHP 2.0-RC1. Being pretty nifty and all, I’ve only come across one challenge that I can’t wrap my mind around. I’ve read the documentation on linking models together (http://www.cakedocs.com/models/associations-linking-models-together.html), but how to I tell CakePHP to search trough a relation table and find the values I’m after? Let me explain.
I have a database structure similar to the following (it has been simplified for the question. PK = Primary Key. FK = Foreign Key )
game
- INT(11) id (PK)
- VARCHAR(100) name
- VARCHAR(40) year
- VARCHAR(10) age
category
- INT(11) id (PK)
- VARCHAR(50) name
game_category
- INT(11) game_id (FK)
- INT(11) category_id (FK)
Explanation to the relationship between these:
A game can have one or more category. This relation is defined in “game_category” table. I want CakePHP to not only find what category id a game has, I want the category name as well when I do $this->Game->find(‘first’) for instance. I would guess CakePHP needs to be told to “continue through the game_category table and onto the category table” and find what the name of each category actually is.
I have these Models
Game.php
<?php
class Game extends AppModel {
var $useTable = 'game';
var $hasMany = array(
'GameCategory' => array(
'fields' => '*',
'className' => 'GameCategory',
)
);
var $hasOne = 'Review';
}
?>
GameCategory.php
<?php
class GameCategory extends AppModel {
var $useTable = 'game_category';
var $belongsTo = 'category';
var $hasMany = array(
'Category' => array(
'fields' => '*',
'foreignKey' => 'category_id',
'className' => 'Category',
'conditions' => array('GameCategory.game_id' => 'Game.id', 'GameCategory.category_id' => 'Category.id'),
)
);
}
?>
Category.php
<?php
class Category extends AppModel {
var $useTable = 'category';
var $belongsTo = 'GameCategory';
}
?>
By the relations defined above, I get results like this:
Array
(
[Game] => Array
(
[id] => 2
[name] => Colonization
[year] => 1995
[age] => 7
)
[GameCategory] => Array
(
[0] => Array
(
[game_id] => 2
[category_id] => 19
)
[1] => Array
(
[game_id] => 2
[category_id] => 16
)
)
)
The only thing remaining is just getting the actual name of each category. I hope some of this made any sense.
Any help is appreciated.
You should see hasAndBelongsToMany (HABTM) in book online and should change table name game_category to games_categories for correct conventions.
Game.php
}
?>