How to use attributes in many-to-many (habtm) associations?
From PHP on Trax
For now if you want to use attributes in habtm associatios you need to add an intermediate model.
Contents |
Example
Employees have Jobs. Each employe gets a certain wage for each of his jobs.
- Employee <-habtm-> Jobs
- Habtm association attribute: pay_rate
Solution: intermediate model "Worker"
- Employee has_many jobs (via Worker)
- Jobs has_many Employees (via Worker)
- Worker
- has the attribute pay_rate
- belongs_to Employee
- belongs_to Job
Code
Models
<?php
class Employee extends ActiveRecord {
public $has_many = array(
"jobs" => array("class_name" => "Worker",
"foreign_key" => "job_id")
);
}
?>
<?php
class Job extends ActiveRecord {
public $has_many = array(
"employees" => array("class_name" => "Worker",
"foreign_key" => "job_id")
);
}
?>
<?php
class Worker extends ActiveRecord {
public $table_name = "workers";
public $belongs_to = "job,employee";
}
?>
Controller
<?php
class JobsController extends ApplicationController {
function index() {
$job = new Job;
$this->jobs = $job->find_all();
}
}
?>
View
<? if(count($jobs)): ?>
<? foreach($jobs as $job): ?>
<p>name: <?=$job->name ?></p>
<? if(count($job->employees)): ?>
<? foreach($job->employees as $employee): ?>
<?=++$i?>. <?=$employee->employee->name?> - pay rate: <?=$employee->pay_rate?><br />
<? endforeach; ?>
<? else: ?>
no employees found for this job.
<? endif; ?>
<? endforeach; ?>
<? else: ?>
no jobs found.
<? endif; ?>
Output
name: Trash Collector no employees found for this job. name: Nose Picker 1. John - pay rate: 4.5 2. Open Face - pay rate: 6.25
