2015-11-03 35 views
0

我正在顯示Web應用程序中管理員的視圖中的表中的所有數據。根據外鍵獲取另一列的值

的SQL看起來是這樣的:

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

我一起工作的視圖的部分如下:

​​

這個工程完全按照預期,但其實不是我想要的以顯示儘可能多的owner_id(int和users表的主鍵)

這將生成一個包含所有值的表,如SQL狀態並且特別是它會使owner_id顯示爲與我的users表有關的外鍵。

我想要做的是實際顯示屬於owner_id的所有者的name,而不是僅顯示id(即... 32)。如何根據引用的外鍵user_idusers表中顯示用戶的關聯name

+0

你能與預期的結果更清晰? – Thamilan

回答

1

您需要使用JOIN來鏈接這兩個表。下面的示例鏈接owner_id上的兩個表格,並在結果中包含user_name。如果兩個表中存在任何列名稱,則需要在SELECT中使用別名。

-- 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 

然後,您可以輸出user_name列在你的PHP像這樣的值:

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

您可以使用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); 

然後在視圖中,它可以被用來作爲

<?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; ?> 
相關問題