Доктрина сброса удаляет существующие значения сущностей - PullRequest
0 голосов
/ 05 октября 2018

Моя сущность:

namespace OAuthBundle\Entity;

use FOS\OAuthServerBundle\Entity\Client as BaseClient;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table("oauth_client")
 */
class Client extends BaseClient
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $name;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param $name
     * @return Client
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

}

В FOS \ OAuthServerBundle \ Model, которая расширяет FOS \ OAuthServerBundle \ Entity \ Client, есть поле, одно из которых является randomId

Когда я пытаюсьвставить некоторую запись с доктриной, например:

    $client = new Client();
    $client->setId(4);
    $client->setRandomId('1wy8z9ayt6kgsw0s4cwk04ogs884cg08kkgg04gso4kckcscog');
    $client->setRedirectUris(array('http://foo.com'));
    $client->setSecret('59az3u43xn4so4g4wswscso4kookwsw00488oogw8kw4w4wgg0');
    $client->setAllowedGrantTypes(array('token', 'authorization_code','http://bar.com/grants/foo' ,'refresh_token'));
    $client->setName('foobarApp');

    $manager->persist($client);
    $manager->flush();

Я получаю от доктрины ошибку:

Doctrine\DBAL\Exception\NotNullConstraintViolationException: An exception occurred while executing 'INSERT INTO oauth_client (name) VALUES (?)' with params ["TestClient"]:

SQLSTATE[HY000]: General error: 1364 Field 'random_id' doesn't have a default value

Дамп $ client-> getRandomId () как раз перед тем, как сброс возвращает правильное значение.

Если я сохраняю и сбрасываю существующую сущность, извлеченную из базы данных и обновленную, она работает нормально.

Кто-нибудь знает, почему доктрина игнорирует некоторые значения сущности при построении запроса вставки?

Структура таблицы:

CREATE TABLE `oauth_client` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `random_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `redirect_uris` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:array)',
  `secret` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `allowed_grant_types` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:array)',
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Класс BaseClient:

class Client implements ClientInterface
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     */
    protected $randomId;

    /**
     * @var string
     */
    protected $secret;

    /**
     * @var array
     */
    protected $redirectUris = array();

    /**
     * @var array
     */
    protected $allowedGrantTypes = array();

    public function __construct()
    {
        $this->allowedGrantTypes[] = OAuth2::GRANT_TYPE_AUTH_CODE;

        $this->setRandomId(Random::generateToken());
        $this->setSecret(Random::generateToken());
    }

    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function setRandomId($random)
    {
        $this->randomId = $random;
    }

    /**
     * {@inheritdoc}
     */
    public function getRandomId()
    {
        return $this->randomId;
    }

    /**
     * {@inheritdoc}
     */
    public function getPublicId()
    {
        return sprintf('%s_%s', $this->getId(), $this->getRandomId());
    }

    /**
     * {@inheritdoc}
     */
    public function setSecret($secret)
    {
        $this->secret = $secret;
    }

    /**
     * {@inheritdoc}
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * {@inheritdoc}
     */
    public function checkSecret($secret)
    {
        return null === $this->secret || $secret === $this->secret;
    }

    /**
     * {@inheritdoc}
     */
    public function setRedirectUris(array $redirectUris)
    {
        $this->redirectUris = $redirectUris;
    }

    /**
     * {@inheritdoc}
     */
    public function getRedirectUris()
    {
        return $this->redirectUris;
    }

    /**
     * {@inheritdoc}
     */
    public function setAllowedGrantTypes(array $grantTypes)
    {
        $this->allowedGrantTypes = $grantTypes;
    }

    /**
     * {@inheritdoc}
     */
    public function getAllowedGrantTypes()
    {
        return $this->allowedGrantTypes;
    }
...