Значение сущности не сохраняется (Doctrine - Symfony 4.1) - PullRequest
0 голосов
/ 19 декабря 2018

Я пытаюсь вставить данные в свою базу данных.У меня все данные хранятся в массиве.Это моя сущность:

<?php declare(strict_types = 1);

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class Application
 * @package App\Entity
 */
class Application
{
    const TYPE_GAME        = 'game';
    const TYPE_DLC         = 'dlc';
    const TYPE_ADVERTISING = 'advertising';
    const TYPE_DEMO        = 'demo';
    const TYPE_MOVIE       = 'movie';
    const TYPE_MOD         = 'mod';
    const TYPE_VIDEO       = 'video';
    const TYPE_SERIES      = 'series';
    const TYPE_EPISODE     = 'episode';
    const TYPE_HARDWARE    = 'hardware';
    const TYPE_OTHER       = 'other';

    /** @var int|null */
    private $id;

    /** @var int|null */
    private $appId;

    /** @var string|null */
    private $name;

    /** @var string|null */
    private $type = self::TYPE_OTHER;

    /** @var string|null */
    private $description = null;

    /** @var bool */
    private $freeGame = false;

    /** @var array  */
    private $categories = [];

    /** @var array */
    private $genres = [];

    /** @var string|null */
    private $headerImage = null;

    /** @var string|null */
    private $backgroundImage = null;

    /** @var array */
    private $supportedLanguages = [];

    /** @var string|null */
    private $legalNotice = null;

    /** @var string|null */
    private $website = null;

    /** @var int|null */
    private $metacriticScore = null;

    /** @var bool */
    private $comingSoon = false;

    /** @var string|null */
    private $supportUrl = null;

    /** @var \DateTime|null */
    private $releaseDate = null;

    /** @var bool */
    private $emptyContent = false;

    /** @var bool */
    private $priceUpdateEnabled = true;

    /** @var \DateTime|null */
    private $lastPriceUpdatedAt = null;

    /** @var bool */
    private $generalUpdateEnabled = true;

    /** @var \DateTime|null */
    private $lastGeneralUpdateAt = null;

    /** @var bool */
    private $enabled = true;

    /**
     * Doctrine relations.
     *
     * We have a one-to-many (self reference) relationship because one application
     * (usually when type = 'Game') can have multiple children (usually type = 'DLC').
     */

    /** @var self|null */
    private $app;

    /** @var ArrayCollection|Application[] */
    private $dlcs;

    /** @var ArrayCollection|Price[] */
    private $prices;

    /**
     * Game constructor.
     */
    public function __construct()
    {
        // OneToMany
        $this->dlcs   = new ArrayCollection();
        $this->prices = new ArrayCollection();
    }

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @param int|null $id
     *
     * @return Application
     */
    public function setId(?int $id): Application
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getAppId(): ?int
    {
        return $this->appId;
    }

    /**
     * @param int|null $appId
     *
     * @return Application
     */
    public function setAppId(?int $appId): Application
    {
        $this->appId = $appId;

        return $this;
    }

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

    /**
     * @param null|string $name
     *
     * @return Application
     */
    public function setName(?string $name): Application
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getType(): ?string
    {
        return $this->type;
    }

    /**
     * @param null|string $type
     *
     * @return Application
     */
    public function setType(?string $type): Application
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getDescription(): ?string
    {
        return $this->description;
    }

    /**
     * @param null|string $description
     *
     * @return Application
     */
    public function setDescription(?string $description): Application
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return bool
     */
    public function isFreeGame(): bool
    {
        return $this->freeGame;
    }

    /**
     * @param bool $freeGame
     *
     * @return Application
     */
    public function setFreeGame(bool $freeGame): Application
    {
        $this->freeGame = $freeGame;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getHeaderImage(): ?string
    {
        return $this->headerImage;
    }

    /**
     * @param null|string $headerImage
     *
     * @return Application
     */
    public function setHeaderImage(?string $headerImage): Application
    {
        $this->headerImage = $headerImage;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getBackgroundImage(): ?string
    {
        return $this->backgroundImage;
    }

    /**
     * @param null|string $backgroundImage
     *
     * @return Application
     */
    public function setBackgroundImage(?string $backgroundImage): Application
    {
        $this->backgroundImage = $backgroundImage;

        return $this;
    }

    /**
     * @return array
     */
    public function getSupportedLanguages(): array
    {
        return $this->supportedLanguages;
    }

    /**
     * @param array $supportedLanguages
     *
     * @return Application
     */
    public function setSupportedLanguages(array $supportedLanguages): Application
    {
        $this->supportedLanguages = $supportedLanguages;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getLegalNotice(): ?string
    {
        return $this->legalNotice;
    }

    /**
     * @param null|string $legalNotice
     *
     * @return Application
     */
    public function setLegalNotice(?string $legalNotice): Application
    {
        $this->legalNotice = $legalNotice;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getWebsite(): ?string
    {
        return $this->website;
    }

    /**
     * @param null|string $website
     *
     * @return Application
     */
    public function setWebsite(?string $website): Application
    {
        $this->website = $website;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getMetacriticScore(): ?int
    {
        return $this->metacriticScore;
    }

    /**
     * @param int|null $metacriticScore
     *
     * @return Application
     */
    public function setMetacriticScore(?int $metacriticScore): Application
    {
        $this->metacriticScore = $metacriticScore;

        return $this;
    }

    /**
     * @return bool
     */
    public function isComingSoon(): bool
    {
        return $this->comingSoon;
    }

    /**
     * @param bool $comingSoon
     *
     * @return Application
     */
    public function setComingSoon(bool $comingSoon): Application
    {
        $this->comingSoon = $comingSoon;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getSupportUrl(): ?string
    {
        return $this->supportUrl;
    }

    /**
     * @param null|string $supportUrl
     *
     * @return Application
     */
    public function setSupportUrl(?string $supportUrl): Application
    {
        $this->supportUrl = $supportUrl;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getReleaseDate(): ?\DateTime
    {
        return $this->releaseDate;
    }

    /**
     * @param \DateTime|null $releaseDate
     *
     * @return Application
     */
    public function setReleaseDate(?\DateTime $releaseDate): Application
    {
        $this->releaseDate = $releaseDate;

        return $this;
    }

    /**
     * @return bool
     */
    public function hasEmptyContent(): bool
    {
        return $this->emptyContent;
    }

    /**
     * @param bool $emptyContent
     *
     * @return Application
     */
    public function setEmptyContent(bool $emptyContent): Application
    {
        $this->emptyContent = $emptyContent;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPriceUpdateEnabled(): bool
    {
        return $this->priceUpdateEnabled;
    }

    /**
     * @param bool $priceUpdateEnabled
     *
     * @return Application
     */
    public function setPriceUpdateEnabled(bool $priceUpdateEnabled): Application
    {
        $this->priceUpdateEnabled = $priceUpdateEnabled;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getLastPriceUpdatedAt(): ?\DateTime
    {
        return $this->lastPriceUpdatedAt;
    }

    /**
     * @param \DateTime|null $lastPriceUpdatedAt
     *
     * @return Application
     */
    public function setLastPriceUpdatedAt(?\DateTime $lastPriceUpdatedAt): Application
    {
        $this->lastPriceUpdatedAt = $lastPriceUpdatedAt;

        return $this;
    }

    /**
     * @return bool
     */
    public function isGeneralUpdateEnabled(): bool
    {
        return $this->generalUpdateEnabled;
    }

    /**
     * @param bool $generalUpdateEnabled
     *
     * @return Application
     */
    public function setGeneralUpdateEnabled(bool $generalUpdateEnabled): Application
    {
        $this->generalUpdateEnabled = $generalUpdateEnabled;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getLastGeneralUpdateAt(): ?\DateTime
    {
        return $this->lastGeneralUpdateAt;
    }

    /**
     * @param \DateTime|null $lastGeneralUpdateAt
     *
     * @return Application
     */
    public function setLastGeneralUpdateAt(?\DateTime $lastGeneralUpdateAt): Application
    {
        $this->lastGeneralUpdateAt = $lastGeneralUpdateAt;

        return $this;
    }

    /**
     * @return bool
     */
    public function isEnabled(): bool
    {
        return $this->enabled;
    }

    /**
     * @param bool $enabled
     *
     * @return Application
     */
    public function setEnabled(bool $enabled): Application
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * @return Application|null
     */
    public function getApp(): ?Application
    {
        return $this->app;
    }

    /**
     * @param Application|null $app
     *
     * @return Application
     */
    public function setApp(?Application $app): Application
    {
        $this->app = $app;

        return $this;
    }

    /**
     * @return Application[]|ArrayCollection
     */
    public function getDlcs()
    {
        return $this->dlcs;
    }

    /**
     * @param Application[]|ArrayCollection $dlcs
     *
     * @return Application
     */
    public function setDlcs($dlcs)
    {
        $this->dlcs = $dlcs;

        return $this;
    }

    /**
     * @return Price[]|ArrayCollection
     */
    public function getPrices()
    {
        return $this->prices;
    }

    /**
     * @param Price[]|ArrayCollection $prices
     *
     * @return Application
     */
    public function setPrices($prices)
    {
        $this->prices = $prices;

        return $this;
    }

    /**
     * @return array
     */
    public function getCategories(): array
    {
        return $this->categories;
    }

    /**
     * @param array $categories
     *
     * @return Application
     */
    public function setCategories(array $categories): Application
    {
        $this->categories = $categories;

        return $this;
    }

    /**
     * @return array
     */
    public function getGenres(): array
    {
        return $this->genres;
    }

    /**
     * @param array $genres
     *
     * @return Application
     */
    public function setGenres(array $genres): Application
    {
        $this->genres = $genres;

        return $this;
    }

    /**
     * Returns all application types.
     *
     * @return array
     */
    public static function getAllTypes(): array
    {
        return [
            self::TYPE_GAME,
            self::TYPE_DLC,
            self::TYPE_ADVERTISING,
            self::TYPE_DEMO,
            self::TYPE_MOVIE,
            self::TYPE_MOD,
            self::TYPE_VIDEO,
            self::TYPE_SERIES,
            self::TYPE_EPISODE,
            self::TYPE_HARDWARE,
            self::TYPE_OTHER
        ];
    }

    /** {@inheritdoc} */
    public function __toString()
    {
        return $this->name ?? '-';
    }
}

А вот мое отображение:

<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity name="App\Entity\Application" table="applications" repository-class="App\Repository\ApplicationRepository">
        <!-- Primary Key generator -->
        <id name="id" type="integer" column="id">
            <generator/>
        </id>

        <!-- Fields -->
        <field name="appId" type="integer" unique="true"/>
        <field name="name" length="255"/>
        <field name="type" length="255"/>
        <field name="description" type="text" nullable="true"/>
        <field name="freeGame" type="boolean"/>
        <field name="categories" type="array"/>
        <field name="genres" type="array"/>
        <field name="headerImage" length="255" nullable="true"/>
        <field name="backgroundImage" length="255" nullable="true"/>
        <field name="supportedLanguages" type="array"/>
        <field name="legalNotice" type="text" nullable="true"/>
        <field name="website" length="255" nullable="true"/>
        <field name="metacriticScore" type="smallint" nullable="true"/>
        <field name="comingSoon" type="boolean"/>
        <field name="supportUrl" length="255" nullable="true"/>
        <field name="releaseDate" type="datetime" nullable="true"/>
        <field name="emptyContent" type="boolean"/>
        <field name="priceUpdateEnabled" type="boolean"/>
        <field name="lastPriceUpdatedAt" type="datetime" nullable="true"/>
        <field name="generalUpdateEnabled" type="boolean"/>
        <field name="lastGeneralUpdateAt" type="datetime" nullable="true"/>
        <field name="enabled" type="boolean"/>

        <!-- OneToMany -->
        <one-to-many field="dlcs" target-entity="App\Entity\Application" mapped-by="app"/>

        <!-- ManyToOne -->
        <many-to-one field="app" target-entity="App\Entity\Application" inversed-by="dlcs"/>
    </entity>
</doctrine-mapping>

База данных была создана без проблем.Я удалил кеш доктрины и локальный кеш.

В настоящее время моя проблема заключается в том, что я пытаюсь сохранить новую сущность: я устанавливаю appId и name, затем сохраняю сущность.Если я dump() сущность перед вызовом persist и flush, все установлено, но после того, как я позвоню persist($app), у меня возвращается эта ошибка:

An exception occurred while executing 'INSERT INTO applications (app_id, name, type, description, free_game, categories, genres, header_image, background_image, supported_languages, legal_notice, website, metacritic_score, coming_soon, support_url, release_date, empty_co
ntent, price_update_enabled, last_price_updated_at, general_update_enabled, last_general_update_at, enabled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [null, "Vector Assault", "other", null, 0, "a:0:{}", "a:0:{}", null, null,
"a:0:{}", null, null, null, 0, null, null, 0, 1, null, 1, null, 1]:\n
\n
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'app_id' cannot be null

Я не имею ни малейшего представления, что не так, потому что, покасоздание базы данных сработало, и сущность выглядит идеально, прежде чем сущность сохранится.Есть идеи?

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018

Вы уверены, что ваше сопоставление хорошее?

В документах они добавляют это column="posted_at" в свое отображение для $postedAt

См .: https://www.doctrine -проект.org / projects / doctrine-orm / en / 2.6 / reference / basic-mapping.html # property-mapping

Возможно, для создания Doctrine предполагается, что вы будете использовать соглашение snake_case для SQL, нов вашей доктрине подчинения нужно знать, в какое поле она отображается?

Кроме этого, я не вижу ничего плохого.

0 голосов
/ 19 декабря 2018

<field name="appId" type="integer" unique="true"/> не может иметь значение NULL.

В операторе SQL оно имеет значение null: INSERT INTO applications (app_id, name ... with params [null, "Vector Assault" Вам нужно либо разрешить appId быть нулевым, либо установить его перед сохранением.

EDIT:Есть орфографическая ошибка.В операторе SQL это app_id, а в вашей сущности - appId.

...