Bramklg
Bramklg

Reputation: 161

Doctrine: array of single values

Looked everywhere but can't find an answer to my question. I'm wondering if its possible with doctrine (symfony) to save an array of strings without making an entity of it.

As an example: A single user has multiple mail addresses (one-to-many). I don't want to save any other meta data with the mail address. E.G.:

<?php
class User {
    private $mailAddresses = array();
    // ...
    public function addEmailAddress($address) {
        $this->mailAddresses[] = $address;
    }
    // ....
}

$user = new User();
$user->addEmailAddress('[email protected]');
$user->addEmailAddress('[email protected]');
$addresses - $user->getEmailAddresses();
// $addresses is a simple array like: array('[email protected]','[email protected]');

Is something like this possbile or do I have to create a UserEmailAddressEntity in order to use the one-to-many relation?

Upvotes: 1

Views: 7008

Answers (2)

webjaros
webjaros

Reputation: 304

I'd use simple_array instead of array, because in your case it is not mandatory to save neither indexes of the array nor data types, so u do not need serialization. And simple_array is basically just

implode(',', $array);

So you will get plain coma separated emails in DB which is quite easy to query. Less space, less unnecessary symbols, a little faster operations.

An entity annotation would be:

/**
* @ORM\Column(type="simple_array")
*/

or if you are using yaml:

fields:
    [...]
    emails:
       type: simple_array
    [...]

If by any reason you are making tables yourself add comment "(DC2Type:simple_array)" to emails column.

If you need to store associative array consider using array instead of simple_array though.

Upvotes: 4

lxg
lxg

Reputation: 13127

If you just need a simple array of strings, you can use the array type:

/**
 * @ORM\Column(type="array")
 */
private $emailAddresses = [];

Doctrine will store it as serialized string, but from the entity’s perspective, it will be an array.

You are free to create methods for adding/managing e-mail adresses (e.g. your addEmailAddress()), if you need more control over single elements without modifying the entire array through the setter.

http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#array-types

Upvotes: 2

Related Questions