简体   繁体   English

原则一对多关联:复合主键问题

[英]Doctrine one-to-many association: Issues with composite primary key

I am trying to populate the below one-to-many doctrine association however I am hitting a problem because every Customer (primary key: id ) has their visits (primary key: customer_id & visitday ) captured in the Visit table (I am deriving visitday as the number of days since 1st Jan 2000 before persisting to the database (since datetime objects can not be in the primary key)): 我正在尝试填充以下一对多的教义关联,但是我遇到了一个问题,因为每个客户 (主键: id )的访问(主键: customer_idvisitday )都在“ 访问”表中捕获了(我派生visitday自2000年1月1日以来一直保留到数据库的天数(因为datetime对象不能在主键中):

Entities 实体

class Customer
{
    /**
     * @ORM\Column(type="integer", options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Visit", mappedBy="visitday")
     */
    protected $visits;

    public function __construct()
    {
        $this->visits = new ArrayCollection();
    }
     /* -- */
}


Class Visit
{

    /**
     * @ORM\Column(name="customer_id", type="integer", options={"unsigned"=true})
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     * @ORM\Id
     */
    private $customer;

    /**
     * @ORM\Column(type="smallint")
     * @ORM\ManyToOne(targetEntity="Customer", inversedBy="visits")
     * @ORM\JoinColumn(name="visitday", referencedColumnName="id")
     * @ORM\Id
     */
    protected $visitday;

     /* -- */
}

My problem is that my Customer objects are not getting populated with the customer's corresponding visits. 我的问题是我的客户对象未填充客户的相应访问。 I assume this is because doctrine can't see that it should also include its own customer ID in the lookup. 我认为这是因为教义无法看到它还应该在查询中包含其自己的客户ID。 Is there a way to fix this? 有没有办法解决这个问题?

I would recommend you to change $visitday attribute to DateTime. 我建议您将$ visitday属性更改为DateTime。 It will be your visit date timestamp. 这将是您的访问日期时间戳。 Then customer attribute should be inversed with visits. 然后,客户属性应与访问次数成反比。

/**
 * @ORM\Column(name="customer_id", type="integer", options={"unsigned"=true})
 * @ORM\ManyToOne(targetEntity="Customer", inversedBy="visits")
 * @ORM\Id
 */
private $customer;

And as an option you could change relation Customer to Visits as ManyToMany. 作为一种选择,您可以将客户关系更改为“多对多访问”。 So you wont have duplicate visit dates. 这样您就不会有重复的访问日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM