作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com
接着,可以为它添加一些条件语句,比如使用entityCondition添加实体本身相关的条件语句:
$query->entityCondition('entity_type', $this->rule->entity_type);
$query->entityCondition('bundle', $this->rule->bundle);
$query->entityCondition('entity_id', $id, '!=');
注意,这里面entity_id,也属于entityCondition的范畴。函数的结构定义是这样的:
public function entityCondition($name, $value, $operator = NULL)
$name,这里的允许值有'entity_type', 'bundle', 'revision_id' 或'entity_id',注意有些实体,比如评论、分类术语,它们不能使用'bundle'。$value就是当前值,$operator是操作符,默认使用“=”,可用的操作符有'=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS', 'IN', 'NOT IN', 'BETWEEN'。注意,后面三个操作符都是作用于数组的。
也可以使用fieldCondition添加字段相关的条件语句:
$query->fieldCondition($this->rule->field_name, $this->rule->col, $this->value);
这是我们这个例子里面用到的。fieldCondition的结构定义是这样的:
public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL)
这里的参数比较多,常用的就是前面四个,后面的我从来没有用过。
在property_validation模块里面的property_validation_unique_validator,还有属性相关的条件语句:
$query->propertyCondition($this->rule->property_name, $this->value) ;
这个成员函数的结构是这样的:
public function propertyCondition($column, $value, $operator = NULL)
$column就是属性名字,$value就是当前值, $operator就是操作符。
获取查询的结果
加了这么多条件语句以后,使用execute()方法就可以获取查询的结果:
$matched_entities = $query->execute();
当然,我们需要注意,返回的结果的数据结构,通常对于返回的结果,进行这样的处理:
foreach ($matched_entities as $entity_type => $entities) {
foreach ($entities as $entity_id => $entity) {
// 这里进行操作
}
}
如果我们这里已经知道了实体的类型,则可以这样处理:
$result = $query->execute();
$entities = entity_load($my_type, array_keys($result[$my_type]));
由于EntitiFieldQuery里面获取到的实体对象,仅仅是一个壳子,所以,我们还需要使用entity_load来加载它。我们在例子中,为了获取到第一个匹配到的实体,这样处理的:
$entity_types = array_keys($matched_entities);
$entity_type = reset($entity_types);
$matched_entity = reset($matched_entities);
$first_match = reset($matched_entity);
$entity_info = entity_get_info($entity_type);
$entity_key_id = $entity_info['entity keys']['id'];
$entitys = entity_load($entity_type, array($first_match->{$entity_key_id}));
$entity = reset($entitys);
这里使用多次使用reset,用来获取一个数组里面的第一个元素,注意,不能够将array_keys($matched_entities)直接传递给reset,如果这样做的话,会提示有语法问题,但是结果仍然是正确的。
使用Count()获取结果记录总数
我们这里的例子是这样的:
$count = $query->count()->execute();
另外,这里面需要说明的是,这些成员函数之间,是可以链式调用的。