Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
accessing other columns with many_to_many
  • If I have a many_to_many relationship is there anyway to access a column in the "in between" table that isn't a foreign key? Here's my setup: Inside of Model_User: protected static $_many_many = array(
    'yeeks' => array(
    'key_from' => 'id',
    'key_through_from' => 'user_id',
    'table_through' => 'items_users',
    'key_through_to' => 'item_id',
    'model_to' => 'Model_Item',
    'key_to' => 'id',
    )
    );
    and here's my accessing that related data:
    Model_User::find('first', array(
    'where' => array(
    'username' => $username,
    ),
    'related' => array(
    'yeeks'
    ),
    ));
    Finally, here's the in between table's syntax:
    CREATE TABLE `items_users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `user_id` int(11) NOT NULL,
    `item_id` int(11) DEFAULT NULL,
    `in_list` int(1) NOT NULL DEFAULT '1',
    PRIMARY KEY (`id`),
    KEY `user_id` (`user_id`),
    KEY `item_id` (`item_id`),
    CONSTRAINT `items_users_ibfk_2` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `items_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=6631 DEFAULT CHARSET=latin1;
    The property i'm trying to access is "in_list"
  • This can be done using Nested relations. Model_User HasMany Model_User_Item
    Model_Item HasMany Model_User_Item Model_User_Item BelongsTo Model_User & BelongsTo Model_Item. After that you can load them like this:
    $user = Model_User::query()->related('user_items')->related('user_items.items')->get_one();
    
    $user->user_items; // holds all the in-between objects
    
    // to get all items
    $items = array();
    foreach ($user->user_items as $ui)
    {
        $items[] = $ui->item;
    }
    

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion