Skip to content

Active Record : How do I use table associations?

Mark Moran edited this page Dec 10, 2013 · 1 revision

Table associations are used by first instantiating a model class from with in one of your controllers. A model class at its very basic is only a few lines of code, but since it inherits from ActiveRecord it already has tons of functionality without doing anything to the model class. Lets make an example to show how the table associations work. Lets say we have a project that belongs to our portfolio, has a project manager, has many milestones, and has and belongs to many categories. First lets make the tables to represent our data.

CREATE TABLE projects (
    id int(11) NOT NULL auto_increment,
    portfolio_id int(11) NOT NULL,
    project_manager_id int(11) NOT NULL,
    name varchar(40) default NULL,
    created_at datetime default NULL,
    PRIMARY KEY  (id)
)

CREATE TABLE portfolios (
    id int(11) NOT NULL auto_increment,
    name varchar(40) default NULL,
    PRIMARY KEY  (id)
)

CREATE TABLE project_managers (
    id int(11) NOT NULL auto_increment,
    first_name varchar(40) default NULL,
    last_name varchar(40) default NULL,
    PRIMARY KEY  (id)
)

CREATE TABLE milestones (
    id int(11) NOT NULL auto_increment,
    project_id int(11) NOT NULL,
    title varchar(150) NOT NULL,
    description text default NULL,
    PRIMARY KEY  (id)
)

CREATE TABLE categories (
    id int(11) NOT NULL auto_increment,
    name varchar(150) NOT NULL,
    PRIMARY KEY  (id)
)

CREATE TABLE categories_projects (
    category_id int(11) NOT NULL,
    project_id int(11) NOT NULL,
    PRIMARY KEY  (id)
)

Now the corresponding Model classes for the above tables. Each of the ... ?> would be its own file, located in the trax/app/models folder. And don't worry you don't have to make these files either, you just use the generator script in the scripts folder. ( ./generator.php model ModelName )

<?
class Project extends ActiveRecord {
    public $belongs_to = "portfolio,project_manager";
    public $has_many = "milestones";
    public $has_and_belongs_to_many = "categories";
}
?>
<?
class Portfolio extends ActiveRecord {
    public $has_many = "projects";
}
?>
<?
class ProjectManager extends ActiveRecord {
    public $has_many = "projects";
}
?>
<?
class Milestone extends ActiveRecord {
    public $has_one = "project";
}
?>
<?
class Category extends ActiveRecord {
    public $has_and_belongs_to_many = "projects";
}
?>

Now lets have a controller called projects. This file would be located in trax/app/controllers. You don't have to make this file either, you just use the generator script in the scripts folder. ( ./generator.php controller ControllerName index show ) this will also create the 2 view files index and show in trax/app/views/projects/index.phtml