Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony money field type and doctrine

What is your strategy to store monetary values with Doctrine? The Symfony's money field is quite handy but how to map this to Doctrine's column? Is there a bundle for this that provides DBAL type?

float or int column types are insufficient because when you deal with money you often deal with currency too. I'm using two fields for this but it's awkward to handle manually.

like image 701
SiliconMind Avatar asked Dec 04 '14 17:12

SiliconMind


1 Answers

Consider using the decimal type:

/**
 * @ORM\Column(type="decimal", precision=7, scale=2)
 */
protected $price = 0;

Note that there are currencies which have three decimal positions. If you intend to use such currencies, the scale parameter should be 3. If you intend to mix currencies with two and three decimal positions, add a trailing 0 if there are only two decimal positions.

Attention: $price will be a string in PHP. You can either cast it to float or multiply it with 100 (or 1000, in the case of currencies with three decimal positions) and cast it to int.


The currency itself is a separate field; it can be a string with the three letter currency code. Or – the clean way – you can create a table with all currencies you’re using and then create a ManyToOne relation for the currency entry.

like image 186
lxg Avatar answered Sep 21 '22 11:09

lxg