@konchober

Почему в Symfony 3.4 через cli маппятся связи, а через web нет?

Symfony 3.4, делаю по документации. Однако получаю ошибки, что он не находит в структуре таблицы поле, которое в сущности является объектом со связанной записью, которое по идее он должен был замаппить в её id, но почему-то этого не делает. Это если запускать через веб, а если запустить этот же код через CLI - всё работает! В обоих случаях env=prod, debug=false.

Читалка yaml-метадаты загружена, пути к файлам указаны правильно. Вот скрин: take.ms/ghLrM
Скрин объекта перед сохранением: take.ms/z5HQB

Вызов метода $this->EntityManager->getClassMetadata(Invoice::class)->getFieldMapping('status');

через веб даёт результат:

{array} [3]
 fieldName = "status"
 type = "integer"
 columnName = "status"


через cli:

{Doctrine\ORM\Mapping\ClassMetadata} [40]
 name = "PaymentsBundle\Entity\Invoice"
 namespace = "PaymentsBundle\Entity"
 rootEntityName = "PaymentsBundle\Entity\Invoice"
 customGeneratorDefinition = null
 customRepositoryClassName = "PaymentsBundle\Repository\InvoiceRepository"
 isMappedSuperclass = false
 isEmbeddedClass = false
 parentClasses = {array} [0]
 subClasses = {array} [0]
 embeddedClasses = {array} [0]
 namedQueries = {array} [0]
 namedNativeQueries = {array} [0]
 sqlResultSetMappings = {array} [0]
 identifier = {array} [1]
 inheritanceType = 1
 generatorType = 4
 fieldMappings = {array} [11]
 fieldNames = {array} [11]
 columnNames = {array} [11]
 discriminatorValue = null
 discriminatorMap = {array} [0]
 discriminatorColumn = null
 table = {array} [1]
 lifecycleCallbacks = {array} [0]
 entityListeners = {array} [2]
 associationMappings = {array} [5]
 isIdentifierComposite = false
 containsForeignIdentifier = false
 idGenerator = {Doctrine\ORM\Id\IdentityGenerator} [1]
 sequenceGeneratorDefinition = null
 tableGeneratorDefinition = null
 changeTrackingPolicy = 1
 isVersioned = null
 versionField = null
 cache = null
 reflClass = {ReflectionClass} [1]
 isReadOnly = false
 namingStrategy = {Doctrine\ORM\Mapping\UnderscoreNamingStrategy} [1]
 reflFields = {array} [16]
 *Doctrine\ORM\Mapping\ClassMetadataInfo*instantiator = {Doctrine\Instantiator\Instantiator} [2]


Есть такая сущность (незначащие поля исключены):

PaymentsBundle\Entity\Invoice:
    type: entity
    table: null
    repositoryClass: PaymentsBundle\Repository\InvoiceRepository
    manyToOne:
        gateway:
            targetEntity: PaymentsBundle\Entity\Invoice\Gateway
        currency:
            targetEntity: PaymentsBundle\Entity\Invoice\Currency
        status:
            targetEntity: PaymentsBundle\Entity\Invoice\Status
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO


Генерирую классы:

php bin/console make:entity --regenerate --overwrite PaymentsBundle


Получаю такое:

class Invoice
{
    private $id;

    private $status;

    private $gateway;

    private $currency;
    
    public function getId(): ?int
    {
        return $this->id;
    }

    public function getStatus(): ?Status
    {
        return $this->status;
    }

    public function setStatus(?Status $status): self
    {
        $this->status = $status;

        return $this;
    }

    public function getGateway(): ?Gateway
    {
        return $this->gateway;
    }

    public function setGateway(?Gateway $gateway): self
    {
        $this->gateway = $gateway;

        return $this;
    }

    public function getCurrency(): ?Currency
    {
        return $this->currency;
    }

    public function setCurrency(?Currency $currency): self
    {
        $this->currency = $currency;

        return $this;
    }
}


Создаю таблицу:

php bin/console doctrine:schema:update --force

Получаю таблицу:

CREATE TABLE `invoice` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status_id` int(11) DEFAULT NULL,
  `gateway_id` int(11) DEFAULT NULL,
  `currency_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQ_90651744E9571A63` (`crypto_id`),
  KEY `IDX_906517446BF700BD` (`status_id`),
  KEY `IDX_90651744577F8E00` (`gateway_id`),
  KEY `IDX_9065174438248176` (`currency_id`),
  CONSTRAINT `FK_9065174438248176` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`),
  CONSTRAINT `FK_90651744577F8E00` FOREIGN KEY (`gateway_id`) REFERENCES `gateway` (`id`),
  CONSTRAINT `FK_906517446BF700BD` FOREIGN KEY (`status_id`) REFERENCES `status` (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci


Заполняю её так:

$Status = $this->EntityManager->getRepository(Invoice\Status::class)->findOneByCode(self::STATUS_NEW);
$Invoice->setStatus($Status);

$Gateway = $this->EntityManager->getRepository(Invoice\Gateway::class)->findOneByCode($data->getGateway() );
$Invoice->setGateway($Gateway);

$Currency = $this->EntityManager->getRepository(Invoice\Currency::class)->findOneByCode($data->getCurrency() );
$Invoice->setCurrency($Currency);

$this->EntityManager->persist($Invoice);
$this->EntityManager->flush();


Получаю ошибку:

An exception occurred while executing 'INSERT INTO invoice (status, gateway, currency) VALUES (?, ?, ?)' with params [{}, {}, {}]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'field list'


console:

#!/usr/bin/env php
<?php

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Debug\Debug;

// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read https://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

set_time_limit(0);

require __DIR__.'/../vendor/autoload.php';

$input = new ArgvInput();
$env = $input->getParameterOption(['--env', '-e'], getenv('SYMFONY_ENV') ?: 'dev', true);
$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption('--no-debug', true) && $env !== 'prod';

if ($debug) {
    Debug::enable();
}

$kernel = new AppKernel($env, $debug);
$application = new Application($kernel);
$application->run($input);


web:

<?php

use Symfony\Component\HttpFoundation\Request;

require __DIR__.'/../vendor/autoload.php';
if (PHP_VERSION_ID < 70000) {
    include_once __DIR__.'/../var/bootstrap.php.cache';
}


$kernel = new AppKernel('prod', false);
if (PHP_VERSION_ID < 70000) {
    $kernel->loadClassCache();
}
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
  • Вопрос задан
  • 226 просмотров
Пригласить эксперта
Ответы на вопрос 1
Keanor
@Keanor
Ведущий разработчик
Почему-то некорректно маппит имя свойства со статусом. Попробуйте name для связи со статусом явно задать.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы