开发者

Kohana 3 ORM: How to get data from pivot table? and all other tables for that matter

开发者 https://www.devze.com 2022-12-31 14:24 出处:网络
I am trying to use ORM to access data stored, in three mysql tables \'users\', \'items\', and a pivot table for the many-many relationship: \'user_item\'

I am trying to use ORM to access data stored, in three mysql tables 'users', 'items', and a pivot table for the many-many relationship: 'user_item'

I followed the guidance from Kohana 3.0.x ORM: Read additional columns in pivot tables

and tried

    $user = ORM::factory('user',1);
    $user->items->find_all();

    $user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
    if ($user_item->loaded()) {
        foreach ($user_item as $pivot) {
            print_r($pivot);
        }    
    }

But I get the SQL error:

"Unknown column 'user_item.id' in 'order clause' [ SELECT user_item.* FROM user_item WHERE user_id = '1' AND item_id = '' ORDER BY user_item.id ASC LIMIT 1 ]"

Which is clearly erroneous because Kohana is trying to order the elements by a column which doesn't exist: user_item.id. This id doesnt exist because the primary keys of this pivot table are the foreign keys of the two other tables, 'users' and 'items'.

Trying to use:

$user_item 开发者_JAVA百科= ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items))
                    ->order_by('item_id', 'ASC');

Makes no difference, as it seems the order_by() or any sql queries are ignored if the second argument of the factory is given.

Another obvious error with that query is that the item_id = '', when it should contain all the elements.

So my question is how can I get access to the data stored in the pivot table, and actually how can I get access to the all items held by a particular user as I even had problems with that?

Thanks


By default, all of Kohana's ORM models expect the table's primary key to be 'id.' You need to set $_primary_key in your model to something else.


$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));

I think you need to provide a single item_id value for this to work, not an array of objects.

Also, to find all entries for a single user you should be able to do this: $user_items = ORM::factory('user_item', array('user_id' => $user));

Does that answer your question?

0

精彩评论

暂无评论...
验证码 换一张
取 消