我正在尝试从数据库中获取按类别划分的内容。我严格要求最多 4 个“人”类型的条目和其他三个“组织”类型的条目。
我试着这样做:
$query = db_select('node', 'n')
->fields('n', array('title','type'))
->fields('i', array('field_image_fid'))
->fields('f', array('uri'))
->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
->condition('type', array('people'))
->range(0,4);
$query->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
$query->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');
$query2 = db_select('node', 'n')
->fields('n', array('title','type'))
->fields('i', array('field_image_fid'))
->fields('f', array('uri'))
->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
->condition('type', array('organization'))
->range(0,4);
$query2->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
$query2->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');
$query->union($query2, 'UNION');
$result = $query
->execute();
问题是这个查询只返回前三个出现的人或组织的组合。所以如果查询返回了三个人,我将看不到任何组织。
我也尝试过这样的事情:
$query = db_query('
SELECT p.title,p.type
FROM node as p
WHERE p.type = :type
LIMIT 4'
, array(':type' => 'people',':type1' => 'organization'))->fetchAll();
$query2 = db_query('
SELECT o.title,o.type
FROM node as o
WHERE o.type = :type1
LIMIT 4'
, array(':type' => 'people',':type1' => 'organization'))->fetchAll();
$query->union($query2, 'UNION');
或像这样:
$result = db_query('
SELECT title,type
FROM {node}
WHERE type = :type
LIMIT 4
UNION ALL
SELECT title,type
FROM {node}
WHERE type = :type1
LIMIT 4'
, array(':type' => 'people',':type1' => 'organization'))->fetchAll();
但这两种方法只返回4个人,没有组织,我的意思是永远不会..
如果你能帮忙,谢谢!