当parent = 0时表示类别
parent = 1表示子类别1连接到类别1(id = 1)
当parent = 2表示子类别2连接到类别2(id = 2)
当父级...等到19个类别(id = 19,父级= 0)
我需要根据用户在类别字段中的选择将子类别的名称带入子类别表单字段中。 类别字段可以正常工作。
id parent name active
1 0 Arts & Entertainment 0
2 0 Automotive 0
3 0 Business & Professional Serv. 1
4 0 Clothing & Accessories 0
5 0 Community & Government 0
6 0 Computers & Electronics 1
7 0 Construction & Contractors 0
8 0 Education 0
9 0 Food & Dining 0
10 0 Health & Medicine 0
11 0 Home & Garden 0
12 0 Industry & Agriculture 0
13 0 Legal & Financial 1
14 0 Media & Communications 0
15 0 Personal Care & Services 0
16 0 Real Estate 0
17 0 Shopping 0
18 0 Sports & Recreation 0
19 0 Travel & Transportation 0
34 1 Acting Schools 1
35 1 Aerial Photographers 1
36 1 Arcades & Amusements 1
37 1 Art Classes 1
38 1 Art Galleries & Dealers 1
39 1 Art Schools 1
1. 这是对类别字段的查询,可以很好地工作,并为我们提供用户的选择($ judgePick)
$db->setQuery('SELECT name FROM #__professional_categ WHERE parent=0 AND active=1 ORDER BY name ASC');
2. 这是试图解决的子类别字段的查询
$judgePick = JRequest::getVar('category');
$db = JFactory::getDBO();
$db->setQuery('SELECT `name` FROM `#__professional_categ` WHERE active = 1 AND (something here...) ORDER BY parent ASC, name ASC);
$result = $db->loadColumn();
if(!$result){
echo "error";
} else {
echo json_encode($result);
}
假设1-要包含='的id。$ db-> quote($ judgePick)
假设2-对于父级> 0必须等于假设1中用户选择的ID
预期结果
子类别字段仅在用户选择ID等于父级的类别字段($ judgePick)中根据用户的选择具有名称。换句话说,例如艺术与娱乐是类别(parent = 0)并具有(id = 1),并且当用户在类别表单字段中选择它时,子类别表单字段应显示所有带有(parent = 1)的名称
答案 0 :(得分:1)
您正在寻找的可能是自我加入:
SELECT x.name
FROM #__professional_categ x
JOIN #__professional_categ y
ON x.parent = y.id
WHERE y.name = ‘. $judgePick .‘
AND x.parent = y.id
AND x.active = 1
您可以在此处检查关于抽象样本的查询: http://www.sqlfiddle.com/#!9/ecc4bb/1/0
由于在代码中输入了,因此您仅会获得所选类别的名称,因此我们也必须在表中选择其ID ,然后我们才能找到并选择子类别的父ID,然后根据该父ID返回子类别的名称。
使用Joomla语法,您的代码和查询应如下所示:
$jinput = JFactory::getApplication()->input;
$judgePick = $jinput->get(‘category’);
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select('x.name')
->from($db->quoteName('#__professional_categ', 'x'))
->join('LEFT', $db->quoteName('#__professional_categ', 'y') . ' ON ' . $db->quoteName('x.parent') .' = '. $db->quoteName('y.id'))
->where($db->quoteName('y.name') .' = '. $db->quote($judgePick))
->andWhere(array($db->quoteName('x.parent').' = '. $db->quoteName('y.id'), $db->quoteName('x.active').' = 1'), $glue = 'AND')
->order($db->quoteName('x.name') . ' ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
$result = $db->loadColumn();
答案 1 :(得分:0)
那
$db->setQuery("SELECT name FROM #__professional_categ WHERE parent=$judgePick AND active=1 ORDER BY name ASC");