Love Fuel?
Donate
About
Forums
Discussions
Login
FuelPHP Forums
Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Orm
Save value into pivot table (Many to many relation)
toxxxa
July 2016
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 ]
Harro
July 2016
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...
Harro
July 2016
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.
toxxxa
July 2016
Thank you, all clear.
Add a Comment
Howdy, Stranger!
It looks like you're new here. If you want to get involved, click one of these buttons!
Sign In
Apply for Membership
Categories
All Discussions
5,089
General
↳ General
3,364
↳ Job Board
13
↳ Installation & Setup
214
Packages
↳ Oil
213
↳ Orm
700
↳ Auth
261
Development
↳ Tips and Tutorials
126
↳ Code share
145
↳ Applications
52
In this Discussion
Harro
July 2016
toxxxa
July 2016