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.
General
How to get data from model associated with foreign key?
JeanAlesi
August 2015
How do I find all Model_Users whose id are in the Model_Group's table?
I have a Model_Group, whose table in DB is 'groups' with a pk of owner_id
If I do,
Model_Group::find('all');
I can get the owner id's of all entries.... But I want to display all usernames (not ids), and they are in Model_Users... How can I do that? thanks
Basically:
groups( id, owner_id, group_name); owner_id references users(id)....
users( id, username, .....)
// TASK: display username for all users.id in groups.ownerid
Harro
August 2015
Accepted Answer
Stop using find(), it's only useful for simple queries, but gets very messy quickly when you want related data, which is the case here.
First, make sure both models define the correct relation: users has_many group, group belongs_to user.
Once done, you can use
$x = Model_Group::query()->related('user')->get();
assuming your belongs_to relation in the Group model is called 'user'.
You can then access the related data like so:
foreach ($x as $group)
{
echo $group->user->username;
}
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
August 2015