简体   繁体   中英

Get value of another column based on foreign key

I am displaying all data from a table in a view for the administrator in a web app.

The SQL looks something like this:

$organizations = $db->query("
    SELECT id, organization_name, owner_id
    FROM organizations
    ORDER BY created_on DESC
  ")->fetchALL(PDO::FETCH_ASSOC);

The part of the view I am working with is as follows:

<?php foreach($organizations as $organization): ?>
   <tr>
     <td><?php echo e($organization['organization_name']); ?></td>
     <td><?php echo e($organization['owner_id']); ?></td>
   </tr>
<?php endforeach; ?>

This works exactly as expected but is not actually what I want to display as far as the owner_id (an int and the primary key of the users table)

This will generate a table with all the values as in the SQL statement and in particular it will render the owner_id to the view which is a foreign key related to my users table.

What I want to do is actually display the name of the owner that belongs to the owner_id instead of just showing the id (ie.. 32). How can I display the associated name of the user from the users table based on the foreign key user_id that is referenced?

You can use JOIN .

$organizations = $db->query("
    SELECT organizations.id, organizations.organization_name, 
    users.user_name
    FROM organizations
    JOIN users ON organizations.owner_id = users.user_id
    ORDER BY organizations.created_on DESC
  ")->fetchALL(PDO::FETCH_ASSOC);

Then in view, it can be used as

<?php foreach($organizations as $organization): ?>
   <tr>
     <td><?php echo e($organization['organization_name']); ?></td>
     <td><?php echo e($organization['user_name']); ?></td>
   </tr>
<?php endforeach; ?>  

You need to use a JOIN to link the two tables. The example below links the two tables on owner_id and includes the user_name in the result. You will need to use an alias in the SELECT in the case that any of the column names exist in both tables.

-- use alias and include user_name
SELECT o.id, o.organization_name, u.user_id, u.user_name 
-- alias the table as "o"
FROM organizations o 
-- alias the table as "u"
JOIN users u 
    -- link the tables here on owner_id
    ON o.owner_id = u.user_id 
ORDER BY o.created_on DESC

You can then output the value of the user_name column in your PHP like so:

<td><?php echo e($organization['user_name']); ?></td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM