How to implement tagging system similar to SO in php/mysql?

前端 未结 3 1527
再見小時候
再見小時候 2021-01-30 18:51

I\'m coding a website in PHP/MySQL and I\'d like to implement a similar to stackoverflow tagging engine. I have 3 relevant tables in DB: 1. Items 2. Tags 3. ItemTagMap (maps tag

3条回答
  •  终归单人心
    2021-01-30 19:33

    You'll want to try to minimize the number of DB calls, putting the heavy work into PHP.

    First, select all your Items from the DB:

    select * from items where (conditions);
    

    Then, create an array of all id's from the result set.

    $ids = array();
    foreach ($items as $item) {
        $ids[] = $item['id'];
    }
    $ids = implode(',' $ids);
    

    Then select all ItemTagMaps and associated tag data for the Item ID's you previously retrieved.

    select map.item_id, t.id, t.name from tags t, item_tag_maps map where t.id = map.tag_id and map.item_id in ($ids);
    

    Now when you loop through your $items array, you can locate all matching tags from the 2nd SQL query you performed as long as it has a matching item_id value.

提交回复
热议问题