anton1x
anton1x

Reputation: 1

How to avoid creating foreign key in Doctrine migration (bidirectional, with Single-table inheritance)?

got one issue with Doctrine. Here is bidirectional ManyToOne-OneToMany association

class InternetPlan extends BaseProduct
...
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\PricingType", inversedBy="internetPlans")
     * @ORM\JoinColumn(name="pricing_type_id", referencedColumnName="id", nullable=true)
     * @JMS\Exclude()
     */
    private $pricingType;

The parent class is

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductsRepository")
 * @ORM\InheritanceType(value="SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap(
 *     {
 *     InternetPlan::type = "InternetPlan",
 *     TVPlan::type = "TVPlan",
 *     AdditionalServicePlan::type = "AdditionalServicePlan",
 *     Device::type = "Device"
 *     }
 *    )
 */
abstract class BaseProduct

And inversed side is

class PricingType
...
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\InternetPlan", mappedBy="pricingType")
     * @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
     * @JMS\Type("object_ids")
     */
    private $internetPlans;

PROBLEM: when i execute doctrine:migrations:diff, it wants to create foreign key constraint in the parent table base product, ignoring my JoinColumn(nullable=true) annotation.

$this->addSql('ALTER TABLE base_product ADD CONSTRAINT FK_E74CBDC94B70279 FOREIGN KEY (pricing_type_id) REFERENCES pricing_type (id)');

But of course, when i'm executing migration then get the following error

 An exception occurred while executing 'ALTER TABLE base_product ADD CONSTRAINT FK_E74CBDC94B70279 FOREIGN KEY (pricing_type_id) REFERENCES pricing_type (id)':                                                                                      

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`taskman42`.`#sql-1_20`, CONSTRAINT `FK_E74CBDC94B70279` FOREIGN KEY (`pricing_type_id`) REFERENCES `pricing_type` (`id`)) 

So i need to remove this line by-hand from every newer migration.

The main question is: How can i avoid this line in every new migration?

Upvotes: 0

Views: 1259

Answers (1)

anton1x
anton1x

Reputation: 1

Jakumi was right, the main reason that i've forget to put JoinColumn(nullable=true) initially... And after this, i've created an object, that was subclass of BaseProduct, so that object has pricing_type_id=0 - that's why foreign key constraint was so ugly.

UPDATE base_product SET pricing_type_id=NULL WHERE pricing_type_id=0

This SQL was helpful

Upvotes: 0

Related Questions