1

我有一个从数据库中获取实体的查询。其中一个字段是“文件名”。我的模型也知道网络路径,并有一个函数“getPath()”,它返回带有相关路径的文件名。

目前,我的数组返回如下:

Array
    (
        [id] => 359
        [thumb] => sound_thumb.png
        ...
    )

但我希望它是这样的:

Array
    (
        [id] => 359
        [thumb] => sound_thumb.png
        [path] => /path/to/file/sound_thumb.png
        ...
    )

有什么方法可以实现这一点$query->getArrayResult();吗?

4

1 回答 1

1

不,您必须直接在您的实体中执行此操作。这里有一个很棒的部分关于文件上传(下面的代码是从这个部分中提取的,并且是我通常用来处理我的实体中的文件路径的代码)。基本上,您可以添加一个getAbsolutePath()可以调用的方法来获取拇指的绝对路径。

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $path;

public function getAbsolutePath()
{
    return null === $this->path
        ? null
        : $this->getUploadRootDir().'/'.$this->path;
}

public function getWebPath()
{
    return null === $this->path
        ? null
        : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // thumbs should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/thumbs';
}

现在,您需要在查询中返回一个对象数组,并且您可以通过调用来访问绝对路径$object->getAbsolutePath()

编辑

如果您确实需要使用以下方法返回数组$query->getArrayResult()

1创建属性$absolutePath

2$absolutePath每次更改路径时更新,使用 prePersist 和 preUpdate生命周期事件

/**
 * @ORM\Column(type="string", nullable=true)
 */
public $absolutePath;

/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function updateAbsolutePath()
{
    $this->absolutePath = $this->getAbsolutePath();
}

现在,你应该有:

Array
    (
        [id] => 359
        [thumb] => sound_thumb.png
        [path] => sound_thumb.png
        [absolutePath] => /path/to/file/sound_thumb.png
        ...
    )
于 2013-04-22T07:41:44.087 回答