I found that Doctrine array types use serialize / unserialize and store data inside "simple" fields like text, integer.
But I have a project with a postgres database with some fields as arrays (mostly text). I want to use this database with Doctrine. Is there any way to handle this?
thank
EDIT:
ps: now i know sql arrays can be good practice thanks to Craig Ringer.
Perhaps I can create a custom type. Is there anyone who has already done this?
EDIT 2:
The problem is half solved:
<?php
namespace mysite\MyBundle\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class TEXTARRAY extends Type
{
const TEXTARRAY = 'textarray';
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getDoctrineTypeMapping('TEXTARRAY');
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return explode('","', trim($value, '{""}') );
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
settype($value, 'array');
$result = array();
foreach ($set as $t) {
if (is_array($t)) {
$result[] = to_pg_array($t);
} else {
$t = str_replace('"', '\\"', $t);
if (! is_numeric($t))
$t = '"' . $t . '"';
$result[] = $t;
}
}
return '{' . implode(",", $result) . '}';
}
public function getName()
{
return self::TEXTARRAY;
}
}
and controller
<?php
namespace mysite\MyBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\Types\Type;
class mysiteMyBundle extends Bundle
{
public function boot() {
Type::addType('textarray', 'mysite\MyBundle\Types\TextArray');
$em = $this->container->get('doctrine.orm.default_entity_manager');
$conn = $em->getConnection();
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('TEXTARRAY', 'textarray');
}
}
I know that I want to search inside these arrays with queries like "myword" = ANY (myarrayfield) ... Does anyone have a key?
- # doctrine2 , DQL, :
<?php
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
class ANY extends FunctionNode {
public $field;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) {
return 'ANY(' .
$this->field->dispatch($sqlWalker) . ')';
}
public function parse(\Doctrine\ORM\Query\Parser $parser) {
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->field = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
, , , ,
$arr[] = $qb->expr()->like($alias.".".$field, $qb->expr()->literal('%'.trim($val).'%') );
if(count($arr) > 0) $qb->Where(new Expr\Orx($arr));
else unset($arr);
, ?:\