Additional many-many relation info

Is there a way to attach addional info to a many-to-many relation and access it through Yii's AR system?

For example:

A table "Person" and a table "Fruit". They have a many-many relationship which is put in the table "PersonFruit". Now we want to know how many apples person X has. We can create person X in the Person table and apple in the Fruit table, but where to put the amount of apples?

The easiest way would be to add a third column to the PersonFruit table, "amount", and just put it in there. However, there seems to be no way to retrieve any extra info from relation tables through Yii's AR system. Does anybody know a solution to this problem?

I’ve been thinking of just adding a method to the Person class which will lazy load the info through DAO when needed, but perhaps there’s a nicer solution to do it directly through AR which I’m overlooking :)

This would be a nice feature to have.  I'd imagine Yii would have to attach this information to the related object (fruits in this case).

I don't think it's currently possible, but Qiang probably knows best.

Actually for your specific example you'd probably want to call count() on the resulting array instead of storing that information in database.  Storing duplicate information like that is a potential time bomb (when is comes mismatched).

But I don’t think that’s what you were asking for :)

Currently there is no specialised solution to this specific problem in Yii.

You can do the following:

Make an extra model for PersonFruit and define all the relations in PersonFruit (belongs_to Person and belongs_to Fruit), in Person (has_many PersonFruit) and in Fruit(has_many PersonFruit).

This way you can access the 'amount' information in PersonFruit using AR.

@olafure

In the example, there would be only 1 apple instance in the Fruit table, so count wouldn't work.

I don't think adding it to the related object would be a good idea as it isn't exactly 'fruit' information but it's really about the relation itself. It might be better to return 2 values: the model object, and an array containing the additional relation info (which would be empty when there is no such info)

@sluderitz

I've considered that solution too, but found doing it manually through DAO in the "person" class more elegant. Your solution would be better if I needed the info both ways though (in my case I only need to know it from the "person" perspective)

I’ll keep my solution for now then, until Yii supports something better (if it ever will :) ). Thanks both.

True lucas.  Lost my mind for a while there.