I use PHPActiveRecord. Assume I've a table Manager and a table Employees. A Manager has multiple Employees and an Employee has one Manager.
I've defined this association:
static $has_many = { array('employee')}
static $belongs_to = { array('manager')}
$manager->employee
gives me an array with Employee instances.
How do I select the oldest Employee? Or the name of the last Employee. How can I use conditions in a associative data? I can extend the association like below:
static $has_many = { array('employee', 'order' => 'age desc', 'limit => 1')}
or
static $has_many = { array('employee', 'order' => 'id desc', 'limit => 1')}
But with this solution I've to create a new association for every new case.
Does a better solution exists? Something like below?
$manager->employee->last()->name
to select the name of the last employee
$manager->employee->find('limit => 1, 'order' => 'age desc')
to select the last employee
This is a bit old of a question, but I feel it at least requires an answer.
You can define multiple relations that you want for the same class. I'm not sure if you explicitly want to avoid that, and sans modifying the framework to have $manager->employee->
return some sort of object you're out of luck.
public static $has_one = array(
array('last_employee', 'class_name'=>'Employee',/** conditions **/ 'foreign_key'=>'manager_id'),
array('oldest_employee', 'class_name'=>'Employee',/** conditions **/ 'foreign_key'=>'manager_id'),
);
You can then call $manager->last_employee;
or $manager->oldest_employee
.
I feel like even something like scopes doesn't exactly give what you want, so this seems like a good solution.