簡體   English   中英

檢查另一個表中是否存在外鍵值?

[英]Check if a foreign key value exists in another table?

我想檢查另一個表中是否存在外鍵值。 我想做的是:我有一張名為Gallery的桌子和另一張名為Posts的桌子。 Posts 是父表,所以 Gallery 帶有 post_id 外鍵。 posts.php頁面上,由於不是每個帖子都有畫廊,我想為每一行顯示一個消息,如“有畫廊”或“沒有畫廊”。 例如:post id 5 有一個畫廊,post number 10 也有,但是 post id 1 沒有畫廊,post id 3 也沒有。我正在考慮這樣的方式: Gallery table, if a gallery_id row has a 'null' value on column post_id, then echo "does not have a gallery." Else echo "has a gallery" if a gallery_id row has a 'null' value on column post_id, then echo "does not have a gallery." Else echo "has a gallery" ,在posts.php上。 有沒有辦法檢查另一個表中是否存在某個值?

SQL 代碼:

CREATE TABLE `gallery` (
 `gallery_id` int(11) NOT NULL AUTO_INCREMENT,
 `picture` varchar(200) NOT NULL,
 `post_id` int(11) NOT NULL,
 `gallery_date` datetime NOT NULL,
 PRIMARY KEY (`gallery_id`),
 KEY `post_id` (`post_id`),
 CONSTRAINT `gallery_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8mb4

我剛試過

<?php
    $checkGallery = new Read();      
    $checkGallery->performQuery('gallery', "WHERE post_id = :post_id", "id_post={$post_id}");      
    if($checkGallery->result()):        
      $affirmative = $checkGallery->result(); 
?>

接着

<td class="values">
  <?= (  $affirmative ? 'This post has a gallery!' : 'No gallery enrolled in this post' );?> 
</td> 

沒有得到滿意的結果。 它省略了某些行,而不是回顯“此帖子中沒有注冊畫廊”

繁榮。 我知道了。

我剛剛執行了一個查詢“ SELECT * FROM gallery WHERE id_post =:id_post ”(考慮到我們在 posts.php 上調用bindValue方法)和 id_post = $id; 所以,SELECT * FROM gallery WHERE id_post = 5 或... WHERE id = 3 等等,結果存儲在 $checkGallery 數組中。)

<?php
  if($checkGallery):
?>
    <td><?= This post has a gallery! ?></td>
<?php else: ?>
    <td><?= No gallery attached to this post.?></td>
<?php endif;?>

並且每一行都動態返回“此帖子有一個畫廊”或“此帖子沒有附加畫廊”。 謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM