0

我正在使用 Datamapper 并希望在结果集中加入相关表的所有列(1:1 关系)。因此,我的代码如下:

$p = new Project();
$arrAll = $p->where("id <", 100)->where_related('outboundform', 'reference_type', 'project')->include_related('outboundform')->get()->all_to_array();
print_r($arrAll);

查询有效,但结果中没有显示表“outboundform”的列,它们被完全忽略!我刚刚检查并生成的 SQL 读取:

SELECT `project` . * , `outboundform`.`id` AS outboundform_id, `outboundform`.`reference_type` AS outboundform_reference_type, `outboundform`.`reference_id` AS outboundform_reference_id, `outboundform`.`created` AS outboundform_created, `outboundform`.`updated` AS outboundform_updated, `outboundform`.`v1` AS outboundform_v1, `outboundform`.`v2` AS outboundform_v2, `outboundform`.`v3` AS outboundform_v3, `outboundform`.`v4` AS outboundform_v4, `outboundform`.`v5` AS outboundform_v5 FROM (`project`) LEFT OUTER JOIN `outboundform` outboundform ON `project`.`id` = `outboundform`.`reference_id` WHERE `project`.`id` <100 AND `outboundform`.`reference_type` = 'project' LIMIT 0 , 30

这没关系,并且在执行时给了我正确的结果。这里有什么 Datamappers 问题?为什么它不返回全部列?

4

1 回答 1

0

相关outboundform行的属性应该可以在以关系名称为前缀的结果对象中访问。所以id变成outboundform_idreference_type变成outboundform_reference_type等等。

问题是all_to_array()不会将这些转移到结果的数组版本中。如果要包含它们,则必须明确列出它们:

$arrAll = $p->/* snip */->all_to_array(array('id', 'name', 'outboundform_id', 'outboundform_reference_type')); // Project fields and outboundform fields too

如果您有任何模型的实例,您可以通过该$instance->fields模型的属性(从数据库表)获取字段列表,并使用这些为all_to_array包含的关系创建前缀名称来创建调用列表。

或者,如果您只需要[]访问字段的方式,您可以实现ArrayAccess这样的接口:

class DataMapper2 extends DataMapper implements ArrayAccess
{ 
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            throw new ErrorException('model instances doesn\'t support pushing new fields');
        } else {
            $this->{$offset} = $value;
        }
    }
    public function offsetExists($offset)
    {
        return isset($this->{$offset});
    }
    public function offsetUnset($offset)
    {
        unset($this->{$offset});
    }
    public function offsetGet($offset)
    {
        return isset($this->{$offset}) ? $this->{$offset} : null;
    }
}
于 2012-11-21T17:20:37.790 回答