0

I have a User model that contains some properties-let's say firstName and lastName-but in my database I store them as first_name and last_name.

inside User Form I use a hydrator like so:

$this->setHydrator(new ClassMethods(true));

The debug shows:

array(5) {
  ["firstName"] => string(13) "my first name"
  ["lastName"] => string(12) "my last name"
  ...
}

Why do the array keys not match the database columns, even I use $this->setHydrator(new ClassMethods(true)); ?

Br.sasa
  • 49
  • 1
  • 8
  • You don't mention how your getters and setters are defined, but I'll venture a guess that you have getFirstName and setFirstName. This is what the ClassMethods hydrator uses. – dualmon Jul 29 '16 at 22:27

2 Answers2

0

I solved the problem for mapping my database columns to User Model by setting naming strategy on the hydrator, here is my code:

$hydrator = new ClassMethods(false);
$namingStrategy = new \Zend\Hydrator\NamingStrategy\UnderscoreNamingStrategy();       
$hydrator->setNamingStrategy($namingStrategy);
Br.sasa
  • 49
  • 1
  • 8
0

In Doctrine you work with an object model separate from your database model meaning that column names and property names are not necessarily the same. In your entity definitions you can explicitly declare your column names and then Doctrine will make sure that the property names are mapped to the correct column names in the UnitOfWork when persisting changes to the database.

You declare column names in the @Column annotations in your entity definitions as follows:

/** @Column(type="string", name="first_name") */
private $firstName;

/** @Column(type="string", name="last_name") */
private $lastName;

You can read more on this in the doctrine documentation chapter 4.3. Property mapping.

Like this you can have an object model that is independent from your database model. So in your debug you see your object model properties, not your database column names. I hope this explanation helps you to understand the differences.

Wilt
  • 41,477
  • 12
  • 152
  • 203