Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Save value into pivot table (Many to many relation)
  • Is it possible to save value into 'table_through'?
    For example, I need to fill `arrange` field in `options_params` table:

    table: params [  id  |  name  ]
    table: options [  id  |  name  ]
    table: options_params [  param_id | option_id | arrange ]
  • HarroHarro
    Accepted Answer
    If you save data in a "through" table, then technically it is no longer a many-to-many relation, it has become two one-to-many relations.

    So you can define it as such, a typical example:

    Student -> many_many -> Course (relation: courses)
    Student -> has_many -> StudentCourse (relation: course)

    Course -> many_many -> Student (relation: students)
    Course -> has_many -> StudentCourse (relation: student)

    StudentCourse -> belongs_to -> Student (relation: student)
    StudentCourse -> belongs_to -> Course (relation: course)

    This requires you to define a model for the through table (here called "StudentCourse"). With this you can do:

    // get some base data
    $student = Model_Student::find(1);

    // get all courses for a student
    $result = $student->courses;

    // loop over the through records
    foreach ($student->course as $through)
    {
        // display the course name
       echo $through->course->name;
    }

    and so on...
  • Note that in a many-many query, through records aren't read and cached, the table is only used to create the join.

    So if you need both through table data and child table data, do something like:

    $result = Model_Student::query()->
        where('id', '=', 1)->
        related('studentcourse')->
        related('studentcourse.course')->
        get();

    To load objects for all three tables in a single query.
  • Thank you, all clear.

Howdy, Stranger!

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

In this Discussion