Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
ManyToMany relation - question with save/update
  • Hi,

    In first, sorry, i'm not very good for write in english...

    I use the relation "ManyToMany" : An "User" can have several "Category", and a "Category" can have several "User".

    The table for this relation is like (users_categorys) : "id", "id_user", "id_category"

    I have a form for create/update an User, in this form i use several "SELECT" input for add/remove "Category". I use js for add/remove "SELECT" from the DOM and their name is like : "categories[1], categories[2], etc..." the number is dynamic (count of "SELECT")

    In the controller i do this :

    <code>
    <?php
    $myUser->categories[] = array();  // I reset all relations
    foreach(Input::post('categories') as $postCategory) {
    $myUser->categories[] = Model_Category::find($postCategory);
    }
    $myUser->save();
    </code>

    It's ok, that work. But ...

    If i create an User and add 2 categories to this user, the table is like :
    id id_user id_category
    1 1 1
    2 1 2

    And now, i want to update this User for edit other fields, but i keep his 2 categories, the table :
    id id_user id_category
    3 1 1
    4 1 2

    He delete 2 rows for add same rows. So he delete old relations for add new relation even if it's the same relation. 
    I think it's normal because i do : $myUser->categories = array();

    But it's not very optimized ? I right ?

    If yes, what is the best solution for my problem ? 
    Perhaps use the attribut "id" in the table "users_categorys", but how can i have access to this ?

    Thank's for read my post
    Good day !

    Syntaxlb
  • Can you create an issue for this on http://github.com/fuel/orm/issues, with a short description, and a link to this page? Then someone can have a look at it.
  • I don't think it's an issue, i think it's just a method.

    But it's work if i do :

    <pre>
    // Reset relations
    $myUser->categories = $myUser->categories;
    unset($myUser->categories);
    // Put relations
    foreach(Input::post('categories') as $postCategory) {
    $myUser->categories[$postCategory] = Model_Category::find($postCategory);
    }
    $myUser->save();
    </pre>

    U know what is the difference ?
  • HarroHarro
    Accepted Answer
    The model keeps track of the related objects, and logs any disconnects through the __unset() magic method.

    When you just assign a new value, it will not call this method, so it doesn't know you want to delete those relations.

Howdy, Stranger!

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

In this Discussion