gregory
gregory

Reputation: 1140

ORM, CRUD and inserting records with many to many relations using FuelPHP

Being completely new to FuelPHP I have a few questions...

I started creating a simple blog application using Oils scaffolding functionality. After that I've set up all relations between my tables following the ORM docs (tables are called 'posts', 'categories' and 'categories_posts' ). Everthing works perfectly and as espected so far, e.g. selecting data with relations (posts and their associated categories).

But now I'm stuck with creating new posts using the form generated by Oil. I've modified it and added a checkbox for every category stored in the DB. Submitting the form will insert a record into the 'posts' table but not into the 'categories_posts' table.

Is this a matter of naming the checkboxes correctly? Or do I need to write a model for the 'categories_posts' table? What am I missing?

Upvotes: 0

Views: 1714

Answers (1)

Quetzy Garcia
Quetzy Garcia

Reputation: 1840

You don't need to create a model for the categories_posts table.

On the action_create() method in Controller_Posts, the database insertion code should be something like:

try
{
    $post = Model_Post::forge();

    $post->title = Input::post('title');
    $post->text = Input::post('text');

    /* the next line will create the relation between the two tables */
    $post->categories[] = Model_Category::find(Input::post('category_id'));

    if ($post and $post->save())
    {
        /* the post has been saved */
    }
    else
    {
        /* something went wrong */
    }
}
catch (\Orm\ValidationFailed $e)
{
    /* validation error */
}

You can check the examples for establishing and breaking has-many relations on the documentation.

Upvotes: 1

Related Questions