57

次のように、エンティティの1つにManyToOne関係があります。

class License {
    // ...
    /**
     * Customer who owns the license
     * 
     * @var \ISE\LicenseManagerBundle\Entity\Customer
     * @ORM\ManyToOne(targetEntity="Customer", inversedBy="licenses")
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    private $customer;
    // ...
}

class Customer {
    // ...
    /**
     * Licenses that were at one point generated for the customer
     * 
     * @var \Doctrine\Common\Collections\ArrayCollection
     * @ORM\OneToMany(targetEntity="License", mappedBy="customer")
     */
    private $licenses;
    // ...
}

これにより、ライセンステーブルの「customer_id」フィールドをnullにできるデータベーススキーマが生成されます。これは、まさに私が望まないことです。

これは、レコードを作成して、参照フィールドにnull値が実際に許可されていることを証明するコードです。

$em = $this->get('doctrine')->getEntityManager();
$license = new License();
// Set some fields - not the reference fields though
$license->setValidUntil(new \DateTime("2012-12-31"));
$license->setCreatedAt(new \DateTime());
// Persist the object
$em->persist($license);
$em->flush();

基本的に、顧客を割り当てずにライセンスを保持したくありません。設定する必要のある注釈はありますか、それとも、Customerオブジェクトをライセンスのコンストラクターに渡す必要がありますか?

私が使用しているデータベースエンジンはMySQLv5.1であり、Symfony2アプリケーションでDoctrine2を使用しています。

4

3 に答える 3

80

https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_joincolumn

注釈nullable = falseに追加:JoinColumn

@ORM\JoinColumn(..., nullable=false)
于 2011-05-26T14:23:17.993 に答える
5

@ zim32がステートメントをどこに置くべきかを教えてくれなかったので、投稿するだけで、試行錯誤しなければなりませんでした。

Yaml:

manyToOne:
    {field}:
        targetEntity: {Entity}
        joinColumn:
            name: {field}
            nullable: false
            referencedColumnName: {id}
        cascade: ['persist']
于 2017-12-19T18:28:42.040 に答える
3

これを行う方法のXMLの例が見つからなかったので、他の誰かがこれを探している場合に備えて、このスニペットをここに残しておきます。

<many-to-one field="author" target-entity="User">
    <join-column name="author_id" referenced-column-name="id" nullable="false" />
</many-to-one>

名前とreferenced-column-name必須です。ドキュメントを参照してください:https ://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/xml-mapping.html#join-column-element

于 2018-07-23T21:09:49.910 に答える