user2003066
user2003066

Reputation: 175

Active Record- How to select a column with relationship?

Projects can have unlimited number of columns (to form a table or something), relationship MANY to MANY. To implement this tbl_project_rel_column is created. It stores project_id, column_id AND pos position of column in Project table.

I am using AC database approach. I have 2 models Project and Column.

Project model's relations method:

public function relations(){
   return array(
...
'columns'=>array(self::MANY_MANY,'Column','tbl_project_rel_column('p_id','c_id')
);
}

Now can get all project's columns using something like this:

$model = Project::model()->findbyPk($p_id);
$columns = $model->columns;

But column doesn't store 'pos'(position) value of it's certain project.

How to get 'pos' value of tpl_project_rel_column table of certain project and certain column?

Upvotes: 0

Views: 1274

Answers (1)

Michael Härtl
Michael Härtl

Reputation: 8587

You can use the through feature instead of MANY_MANY. It may also be useful to index the results by the position column. Try something like this:

public function relations()
{
    return array(
        'projectColumns' => array(self::HAS_MANY, 'ProjectRelColumn', 'p_id', 'index'=>'position'),
        'columns' => array(self::HAS_MANY, 'Column', 'c_id', 'through'=>'projectColumns'),
}

Now you can query for projects with columns like this:

$projects = Project::model()->with('columns')->findAll();
foreach($projects as $project) {
    // projectColumns are indexed by position. You can sort by this now:
    ksort($project->projectColumns)
    foreach($project->projectColumns as $pos => $projectColumn)
        echo "Pos: $pos Column: {$projectColumn->column->name}";
}

Upvotes: 3

Related Questions