将post,tag,category插入mysql的最佳方法是什么?

时间:2017-02-11 13:31:43

标签: php mysql pdo

嗨,我有这些表格:

Table Name | column 1 | column 2 | ...   
Posts       | ID       | Title    | description  
Tags        | ID       | Name  
Categories  | ID       | Title    | Parent-ID  
Post-Tag    | ID       | post-id  | tag-id  
Post-Cat    | ID       | post-id  | cat-id

如何插入带有标签的1个帖子&类别? 我可以插入一个这样的新帖子:

$stmt = $conn->prepare("INSERT INTO Posts (title, description) VALUES ( :title, :desc)");

$stmt->bindParam(':title', $title);
$stmt->bindParam(':desc', $description);

$post_id = $conn->lastInsertId();

我每次只有一个帖子,但可能有五个标签& 2个类别 我如何检查标签/类别是否存在&如果存在获得其ID&如果没有插入它然后得到id&将它插入Post-tag / Post-cat表?!

1 个答案:

答案 0 :(得分:0)

这里有一些示例代码,可以让您了解它是如何工作的......

<?php
class PostRepository {

    public static function tagExists($tag) {
        // do your query here and return tag-id if it exists and false if it doesnt exist
    }

    public static function insertTag($tag) {
        // do your insert query here and return the inserted id and false on failure
    }

    public static function insertPostTag($id_post, $id_tag) {
        // do your insert query here and return the inserted id
    }

    public static function insertPost($title, $description, $arr_tags) {

        $conn = PdoHelper::getPdoInstance(); // get your conn-obj however...

        $sql = "INSERT INTO `Posts`  (title, description) VALUES ( :title, :desc)";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':desc', $description);

        $post_id = $conn->lastInsertId();

        foreach($arr_tags as $tag) {
            $existing_tag = self::tagExists($tag);
            if(!$existing_tag) {
                $existing_tag = self::insertTag($tag);
            }
            self::insertPostTag($post_id, $existing_tag);
        }

    }
}