Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
advanced create
  • Let's say I have an online library. Now, let's say I have a proper author model and book model with a "has many" relationship. Let's also say I have a form that allows you to create an author AND a book by that author at the same time. How would this be done? Or, rather, what is the best, most efficient way to create these records? I've tried something like this (with no luck):
    $author = new Model_Author();
    $author->name = Input::post('author_name');
    $author->books->title = Input::post('book_title');
    $author->save();
    

    and something like this:
    $author = new Model_Author();
    $author->name = Input::post('author_name');
    $author->books = new Model_Book();
    $author->books->title = Input::post('book_title');
    $author->save();
    

    And I've also tried countless other permutations of this. I'm sure the flaws here are blatant to someone familiar with orm so please forgive the ignorance. If someone could at least post an example for me, that would be great.
  • $author->books is an array, thus assigning a model to it will cause errors and assigning a property to it wouldn't work either. This is how I'd do it:
    $author = new Model_Author();
    $author->name = Input::post('author_name');
    $book = new Model_Book();
    $book->title = Input::post('book_title');
    $author->books[] = $book;
    $author->save();
    

    You can also do this:
    $author = new Model_Author();
    $author->name = Input::post('author_name');
    $author->books[1] = new Model_Book();
    $author->books[1]->title = Input::post('book_title');
    $author->save();
    

    But if you do you must be very sure there isn't already an existing relation with index 1. After retrieval from the DB and after saving it to the DB the relations are indexed by their primary key, even if you didn't index them by it yourself before saving.
  • Worked great, thanks.

Howdy, Stranger!

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

In this Discussion