1

データベースからエンティティをフェッチするクエリがあります。フィールドの 1 つは「ファイル名」です。私のモデルは Web パスも認識しており、関連するパスでファイル名を返す関数「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

2prePersist および preUpdateライフサイクル イベント$absolutePathを使用して、パスを変更するたびに更新します。

/**
 * @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 に答える