Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to get data from model associated with foreign key?
  • 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
  • HarroHarro
    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;
    }

Howdy, Stranger!

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

In this Discussion