Symfony entitymanager отказывается вставлять один столбец - PullRequest
0 голосов
/ 27 февраля 2020

Я пытаюсь сохранить и залить sh новую сущность в мою базу данных. Однако один столбец: tblCompaniesServicesId не вставляется вместе с другими данными, что приводит к ответу SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tbl_companies_services_id' cannot be null.

Когда я dd($entityManager->getUnitOfWork()->getScheduledEntityInsertions()); после сохранения новой сущности, я получаю это: ( Обратите внимание, что tblCompaniesServicesId имеет значение 12.)

array:1 [
  "0000000013992b51000000003eb8a5e6" => TblCompaniesServicesContracts {#1500
    -tblCompaniesServicesContractsId: null
    -tblCompaniesServicesId: 12
    -tblCompaniesServicesDiscountsId: null
    -tblCompaniesId: 9999
    -tblCompaniesLocationsId: null
    -tblCompaniesCustomersId: 9999
    -contractOrdernr: null
    -contractName: "yeetus"
    -contractDate: null
    -contractPrice: null
    -contractPricetax: null
    -contractTax: null
    -contractPayed: "0"
    -contractUntil: null
    -contractActive: "1"
    -contractMonths: null
    -contractReminder: "0"
    -discountTitle: null
    -discountPrice: null
    -discountPercentage: null
    -discountPriceStartup: null
    -discountPercentageStartup: null
    -transactionId: null
    -responseId: null
    -responseStatus: null
    -responseStatusNl: null
    -responseCheck: null
    -responseTransactionid: null
    -responseAmount: null
    -responseCurrency: null
    -responsePayed: null
    -responseCustname: null
    -responseCustaccount: null
    -responseCustcity: null
    -contractMemo: null
    -contractAmountPerPeriod: "0.00"
    -contractPeriodInMonths: "1"
    -contractContractInMonths: "12"
    -contractTerminateWithinContract: "1"
    -contractNoticePeriodInMonths: "1"
    -contractExtendInMonths: "12"
    -contractStartupAmount: "0.00"
    -contractPayInOnce: "1"
    -contractPayInOnceDiscount: "10"
    -contractTerminated: "0"
    -contractTerminatedDate: null
    -contractPaymentDay: "1"
    -contractPaymentDayNextmonth: null
    -contractReversalFee: null
    -contractSignature: null
    -contractEmail: null
    -contractIban: null
    -contractIbanName: null
    -contractCredits: "0.00"
    -contractApproved: "0"
    -contractMd5: null
    -payproInstallmentId: null
    -pdfHash: null
    -createdAt: null
    -guardianFirstname: null
    -guardianLastname: null
    -guardianEmail: null
    -guardianBirthdate: null
    -guardianSignature: null
    -signupValue: null
    -service: null
    -customer: null
    -contractAffiliateId: null
    -serviceAmountFirstmonth: null
  }
]

Ответ, который я получаю, таков: (теперь tblCompaniesServicesId не имеет значения.) An exception occurred while executing 'INSERT INTO tbl_companies_services_contracts (tbl_companies_services_id, tbl_companies_services_discounts_id, tbl_companies_id, tbl_companies_locations_id, tbl_companies_customers_id, contract_ordernr, contract_name, contract_date, contract_price, contract_pricetax, contract_tax, contract_payed, contract_until, contract_active, contract_months, contract_reminder, discount_title, discount_price, discount_percentage, discount_price_startup, discount_percentage_startup, transaction_id, response_id, response_status, response_status_nl, response_check, response_transactionid, response_amount, response_currency, response_payed, response_custname, response_custaccount, response_custcity, contract_memo, contract_amount_per_period, contract_period_in_months, contract_contract_in_months, contract_terminate_within_contract, contract_notice_period_in_months, contract_extend_in_months, contract_startup_amount, contract_pay_in_once, contract_pay_in_once_discount, contract_terminated, contract_terminated_date, contract_payment_day, contract_payment_day_nextmonth, contract_reversal_fee, contract_signature, contract_email, contract_iban, contract_iban_name, contract_credits, contract_approved, contract_md5, paypro_installment_id, pdf_hash, contract_created_at, guardian_firstname, guardian_lastname, guardian_email, guardian_birthdate, guardian_signature, signup_value, contract_affiliate_id, service_amount_firstmonth) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [null, null, 9999, null, null, null, \"yeetus\", null, null, null, null, \"0\", null, \"1\", null, \"0\", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, \"0.00\", \"1\", \"12\", \"1\", \"1\", \"12\", \"0.00\", \"1\", \"10\", \"0\", null, \"1\", null, null, null, null, null, null, \"0.00\", \"0\", null, null, null, null, null, null, null, null, null, null, null, null]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tbl_companies_services_id' cannot be null

тело из моего запроса:

{
    "tblCompaniesServicesId": 12,
    "tblCompaniesCustomersId": 9999,
    "contractName": "yeetus"
}

TblCompaniesServicesContracts сущность (только соответствующие атрибуты и методы, из-за ограничения по количеству символов, вы можете видеть, насколько велика эта сущность из дампа, опубликованного выше):

<?php

namespace App\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * TblCompaniesServicesContracts
 *
 * @ORM\Table(name="tbl_companies_services_contracts")
 * @ORM\Entity(repositoryClass="App\Repository\TblCompaniesServicesContractsRepository")
 */
class TblCompaniesServicesContracts implements \JsonSerializable
{
    /**
     * @var int
     *
     * @ORM\Column(name="tbl_companies_services_id", type="integer", nullable=false)
     */
    private $tblCompaniesServicesId;

    public function getTblCompaniesServicesId(): ?int
    {
        return $this->tblCompaniesServicesId;
    }

    public function setTblCompaniesServicesId(int $tblCompaniesServicesId): self
    {
        $this->tblCompaniesServicesId = $tblCompaniesServicesId;

        return $this;
    }
}

Соответствующая функция в моем контроллере: (опять же, ограничение символов)

    public function addCompaniesServicesContracts(Request $request, EntityManagerInterface $entityManager, TblCompaniesServicesContractsRepository $tblCompaniesServicesContractsRepository, TokenStorageInterface $tokenStorageInterface, JWTTokenManagerInterface $jwtManager, TblCompaniesUsersRepository $tblCompaniesUsersRepository)
    {
        try {
            $decodedJwtToken = $jwtManager->decode($tokenStorageInterface->getToken());
            $user = $tblCompaniesUsersRepository->findOneByUsername($decodedJwtToken["username"]);
            $request = $this->transformJsonBody($request);
            $tblCompaniesServicesContracts = new TblCompaniesServicesContracts();
            $parameters = $request->request->all();

            if ($user->getCompany() == null) { // check if contract company id is same as company id of the user who requested
                throw new \Exception(403);
            }

            if ($user->getSuperAdmin() != true) { // check if user authorisation level is high enough
                throw new \Exception(403);
            }

            while ($parameter = current($parameters)) {
                if (key($parameters) == "tblCompaniesId") {
                    throw new \Exception(422);
                }
                else {
                    $newValue = $this->setContractValues($tblCompaniesServicesContracts, key($parameters), $parameter);
                    if (is_numeric($newValue)) {
                        throw new \Exception($newValue);
                    }
                    else {
                        $tblCompaniesServicesContracts = $newValue;
                    }
                }
                next($parameters);
            }

            if ($tblCompaniesServicesContracts->getTblCompaniesServicesId() == null) {
                throw new \Exception(422);
            }

            $tblCompaniesServicesContracts->setTblCompaniesId($user->getCompany());
            $entityManager->persist($tblCompaniesServicesContracts);
            //dd($entityManager->getUnitOfWork()->getScheduledEntityInsertions());
            $entityManager->flush();


            $data = [
                'status' => 200,
                'success' => "contract added",
                'companiesServicesContractsId' => $tblCompaniesServicesContracts->getTblCompaniesServicesContractsId(),
            ];
            return $this->response($data);
        }
        catch (\Exception $e) {
            switch ($e->getMessage()) {
                case 403:
                    $data = [
                        'status' => 403,
                        'errors' => "You shall not pass! Forbidden, access denied.",
                    ];
                    return $this->response($data, 422);
                    break;
                case 422:
                    $data = [
                        'status' => 422,
                        'errors' => "Data not valid",
                    ];
                    return $this->response($data, 422);
                    break;
                default:
                    $data = [
                        'status' => $e->getMessage(),
                        'errors' => "The foxes are on the loose, unknown error!",
                    ];
                    return $this->response($data, 422);
                    break;
            }
        }
    }

1 Ответ

0 голосов
/ 27 февраля 2020

Все еще не знаю, почему это идет не так, но функция, которая требует другого объекта, должна это исправить. И эта функция должна вызываться вместо функции, которую вы ожидаете использовать.

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\TblCompaniesServices", inversedBy="contracts")
 * @ORM\JoinColumn(name="tbl_companies_services_id", referencedColumnName="tbl_companies_services_id", nullable=true)
 */
private $service;

public function setService(?TblCompaniesServices $service): self
{
    $this->service = $service;

    return $this;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...