CodeIgniter Forums

Full Version: How to represent this relationship in DataMapper
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum


I'm using DataMapper with CodeIgniter and I'm having problems representing this relationship between two entities — Session and User.

- A Session has 1 author (User);
- A Session can be accessed by many Users.

I can successfully implement the first relationship alone, without the need of a join table, and I can also implement the second relationship alone, with a join table. But I can't get the two working at the same time.

How should I define them?


El Forum

For one of the two you'll have to use an advanced relationship definition, because you can use the other side only once as relation name. Have a look in the documentation, it has an example of two relations between the same two models.

El Forum

I did that.

Here's how I defined them:

class Session extends DataMapper {
var $has_many = array('track', 'user');
var $has_one = array('author' => array('class' => 'user', 'other_field' => 'authored'));

class User extends DataMapper {
var $has_many = array('track', 'user', 'authored' => array('class' => 'session', 'other_field' => 'author'));

echo("Author name: " . $s->author->name . "<br>");
echo("Author e-mail: " . $s->author->email . "<br>");

And this is the error message:

Quote:Error Number: 1054

Unknown column 'authored_sessions_users.authored_id' in 'where clause'

SELECT `users`.* FROM (`users`) LEFT OUTER JOIN `sessions_users` authored_sessions_users ON `users`.`id` = `authored_sessions_users`.`author_id` WHERE `authored_sessions_users`.`authored_id` = 2

I have tried to do this in many different ways. I've also tried to specify the foreign-key names, etc.

Thanks for your reply!

EDIT: This is weird because I just tried to output information about the author (the one-to-many part), so it shouldn't go to the join table, sessions_users. Right?

El Forum

I've been trying in a lot of different ways with no luck. Sad

El Forum

Your query shows it's using "authored_id", which is a field that does not exist.

With this configuration, either name your FK like this, or use the "join_self"/"join_other" fields of the relationship definition to control the name of the FK.

Note that the column MUST end on "_id", and the name you specify in the relationship definition MUST NOT.