Reputation: 13800
I have a simple crud application in Kohana 3.3, with a few different types of data or models. Let’s say those models are:
I have a table for each of those models, but the tables aren’t related to one another in any way. I’ve been trying to define relationships with ORM, but I’m still confused. As an example:
I have a number of locations. Each location has many users.
I know I can define that with:
class Model_Location extends ORM {
/**
* A location has many users
*
* @var array Relationships
*/
protected $_has_many = array(
'users' => array('model' => 'user'),
);
}
As I understand it, I can connect the two by referencing the ID of the parent location from the row in the user table. However, what if each user can belong to many locations? Am I supposed to store serialised data in a foreign key? Should I create a “look-up table”? If so, how should it look?
How can I for example, query the database for a location and all users attached to it? Is ORM even the right technology to be using for this kind of thing?
Upvotes: 0
Views: 138
Reputation: 5644
You are looking for the through
parameter, have a look at the docs.
You need an extra table that stores the ids of both models
table users_locations
, fields: user_id
and location_id
(both indexed, of course)
And in your model:
protected $_has_many = array(
'users' => array(
'model' => 'user'
'through' => 'users_locations',
),
);
And vice versa in the user model:
protected $_has_many = array(
'locations' => array(
'model' => 'location'
'through' => 'users_locations',
),
);
Upvotes: 2