0
votes

As i know, getting result from database using doctrine will return an array of object and its field name is the entity property name but not table column name.

My HomeBanner Entity:

class HomeBanner
{
  /**
   * @ORM\Id()
   * @ORM\GeneratedValue()
   * @ORM\Column(type="integer")
   */
  private $id;

  /**
   * @ORM\Column(type="string", length=255)
   */
  private $imageName;

  /**
   * @ORM\Column(type="string", length=255)
   */
  private $caption;

  /**
   * @ORM\Column(type="date")
   */
  private $updatedAt;
}

In database table, the column name is like:

---------------
|  id         |
|  image_name |
|  caption    |
|  updated_at |
---------------

In HomeBannerRepository, i create a new method and return array result:

return $this->createQueryBuilder('h')->getQuery()->getArrayResult();

It give me:

[id] => 1,
[imageName] => test.jpg,
[caption]  =>  helloworld,
[updatedAt] => 2019/06/18

But what i want is:

[id] => 1,
[image_name] => test.jpg,
[caption]  =>  helloworld,
[updated_at] => 2019/06/18

Is there another way to get result with table column name (not object property name) without directly with SQL query?

1
Rename your entity property to match the table column name? - ehymel
I did that before, but if i want to render a twig template, it will throw error. For example: Could not find method for getimage_name().. bla bla bla etc since the entity maker will generate getImageName() but not getimage_name() regardless i put image_name or imageName as property name. - Vui
You have to change the name of the getters/setters. - ehymel

1 Answers

0
votes

you can get the array keys name and return another array with the new key names:

$key_name = strtolower(preg_replace('/\B([A-Z])/', '_$1', $keyName));

although I strongly recommend to change your entity property names to match the table name