Reputation: 42350
When using Kohana 3's ORM models, what is the best way to get data from fields of related models? For example, I have an employee, who has one company, and has many assignments. How would I go about getting data from fields in the company model and assignment model(s) (i.e. in a has_one and a has_many relationship)?
EDIT: as requested, here are the models in question.
User Model
class Model_User extends ORM {
protected $_table_name = 'user';
protected $_primary_key = 'id';
protected $_primary_val = 'username';
protected $_has_many = array(
'task' => array(
'model' => 'task',
'foreign_key' => 'user',
),
);
protected $_belongs_to = array(
'company' => array(
'model' => 'company',
'foreign_key' => 'company'
),
);
Task Model
class Model_Task extends ORM {
protected $_table_name = 'tasks';
protected $_primary_key = 'id';
protected $_primary_val = 'name';
protected $_belongs_to = array(
'project' => array(
'model' => 'project',
'foreign_key' => 'project'
),
'user' => array(
'model' => 'user',
'foreign_key' => 'user'
),
);
Company Model
class Model_Company extends ORM {
protected $_table_name = 'companies';
protected $_primary_key = 'id';
protected $_primary_val = 'name';
protected $_has_many = array(
'user' => array(
'model' => 'user',
'foreign_key' => 'company'
),
);
}
Code Throwing Error, From Controller
$users = ORM::factory('user')->find_all();
$list = array();
foreach($users as $user) {
$list[$user->id] = array(
'username' => $user->username,
'email' => $user->email,
'company' => $user->company->name //error:Trying to get property of non-object
)
}
Upvotes: 2
Views: 3261
Reputation: 5483
users
table? Seems like its a company
instead of company_id
. If so, you can rename this foreign key or relation name.Upvotes: 2
Reputation: 13430
Well, if your employee can only belong to one company then to access the company would be done like so:
$company = $employee->company;
You can then access $company
properties (fields) like you would with any other model.
I believe there's no limit to the depth of relations you can access, so doing
$assignments $employee->company->assignments->find_all();
is possible. Make note of the find_all();
where you expect to have more than one record returned.
Upvotes: 0
Reputation: 391
To get the company you would do
$employee->company
So you can get the company properties with
$employee->company->property
To get the assignments you would do
$employee->company->assignments->find_all();
You can also chain other query methods such as ->where() before you call find_all() or find().
Upvotes: 0