Search code examples
phpormfuelphp

FuelPHP: Add multiple many-to-many relationships


I have two MySQL tables, subjects and books, and a third table to define many-to-many relationships between these two:

CREATE TABLE IF NOT EXISTS `books` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `isbn13` char(13) NOT NULL,
  `isbn10` char(10) NOT NULL,
  `author` varchar(255) NOT NULL,
  `language` varchar(100) NOT NULL,
  `edition` smallint(6) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

CREATE TABLE IF NOT EXISTS `books_subjects` (
  `subject_id` int(11) NOT NULL,
  `book_id` int(11) NOT NULL,
  PRIMARY KEY  (`subject_id`,`book_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `subjects` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `institution_id` mediumint(9) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

To add a new subject, I use the ORM package:

<?php    
$subject = Model_Subject::forge(array(
    'name' => Input::post('name'),
    'institution_id' => Input::post('institution_id'),
));

$subject->save();
?>

I have also added the many-to-many relationship to the Subject model:

protected static $_many_many = array('books');

Retrieving subjects with their assigned books works fine (I have added a few records to the books_subjects table manually), but I don't know how to add the relationships using the ORM package. The relationships are in an array like this (retrieved by using Input::post()):

  array(2) {
    [0]=>
    string(1) "2"
    [1]=>
    string(1) "3"
  }

For someone with some experience with FuelPHP this should be pretty easy, but I just cant seem to figure it out...

Thanks in advance for helping me out!


Solution

  • Try

    <?php    
    $subject = Model_Subject::forge(array(
        'name' => Input::post('name'),
        'institution_id' => Input::post('institution_id'),
    ));
    
    $subject->save();
    
    foreach (Input::post('books') as $book_id) {
        $subject->books[] = Model_Book::find($book_id);
    }
    
    $subject->save();
    ?>