我在 CakePHP(最新版本)中编写了一个标签搜索,但与 CakePHP 的其余部分的简单程度相比,我所做的解决方案似乎过于复杂。希望有人可以为我指明正确的方向或帮助我改进当前的解决方案。
我的应用程序中的每个用户都可以用标签标记自己,例如:php、objective-c、javascript、jquery。不同类型的用户可以搜索具有特定标签的用户。他们可能会搜索:php、objective-c、ios。我需要按照他们匹配多少标签的顺序返回一个用户数组,具有所有 3 个标签的用户将出现在数组的顶部。
下面是数据库示例和我的解决方案。我真的很感谢任何关于改进这一点的帮助。
[数据库]
[解决方案]
//Search Array
//Format: array('objective-c', 'javascript', 'jquery', 'php')
$tag_array = explode(",", $this->request->data["User"]["search"]);
//Get Tag IDs - array([id] => [id])
//Format: array([1] => '1', [2] => '2', [4] => '4', [15] => '15')
$result_tag_ids = $this->User->TagsUser->Tag->find('list', array(
'conditions' => array(
"Tag.name" => $tag_array
),
'fields' => array('Tag.id')
));
//Get User IDs - array([id] => [id])
//Format: array([24] => '24', [24] => '24', [26] => 26, [27] => '27')
$result_user_ids = $this->User->TagsUser->find('list', array(
'conditions' => array(
"TagsUser.tag_id" => $result_tag_ids
),
'fields' => array('TagsUser.user_id')
));
//Remove Duplicate user ids and add a count of how many tags matched & sort the array in that order
//Format: array([26] => 1, [24] => 2, [27] => 3)
$counted_user_ids = array_count_values($result_user_ids);
asort($counted_user_ids);
//Get the keys (user_ids)
$list_user_ids = array_keys($counted_user_ids);
//Get these users in the order of the sorted array
$search_result = $this->User->find('all', array(
'conditions' => array(
"User.id" => $list_user_ids
),
'order' => 'FIELD(User.id,' . implode(" ,", $list_user_ids) . ')'
));