【问题标题】:JoinColumns/Composite keys with php attributes具有 php 属性的 JoinColumns/Composite 键
【发布时间】:2023-01-05 21:28:50
【问题描述】:

如何使用 PHP 属性声明 joinColumns/复合键。一直找不到正确的方法,也没有记录 (https://www.doctrine-project.org/projects/doctrine-orm/en/2.11/reference/attributes-reference.html)

实体

评论.php

#[ORM\Entity(repositoryClass: CommentRepository::class)]
class Comment
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: PullRequest::class, inversedBy: 'comments')]
    #[ORM\JoinColumn(name: 'pull_request_id', referencedColumnName: 'id')]
    #[ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'repo_id')]
    private $pullRequest;
}

PullRequest.php

#[ORM\Entity(repositoryClass: PullRequestRepository::class)]
class PullRequest
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', unique: false)]
    private $id;

    #[ORM\Id]
    #[ORM\ManyToOne(targetEntity: Repo::class, inversedBy: 'pullRequests')]
    #[ORM\JoinColumn(nullable: false)]
    private $repo;

    #[ORM\OneToMany(mappedBy: 'pullRequest', targetEntity: Comment::class, orphanRemoval: true)]
    private $comments;

}

【问题讨论】:

    标签: php doctrine-orm doctrine


    【解决方案1】:

    我今天遇到了同样的问题,并设法找到了解决方法。 JoinColumns 似乎确实不能作为 PHP8 属性使用,至少在 Doctrine ORM 2.11 和即将到来的 2.12 / 3.0 中是这样。

    但是,您可以通过将连接列定义移动到类级别的 AssociationsOverride attribute 来解决此问题,如下所示:

    #[ORMEntity(repositoryClass: CommentRepository::class)]
    #[ORMAssociationOverrides([
        new ORMAssociationOverride(
            name: 'pullRequest',
            joinColumns: [
                new ORMJoinColumn(name: 'pull_request_id', referencedColumnName: 'id'),
                new ORMJoinColumn(name: 'repo_id', referencedColumnName: 'repo_id')
            ]
        )
    ])]
    class Comment
    {
        #[ORMId]
        #[ORMColumn(type: 'integer')]
        private $id;
    
        #[ORMManyToOne(targetEntity: PullRequest::class, inversedBy: 'comments')]
        private $pullRequest;
    }
    

    【讨论】:

      【解决方案2】:

      根据https://github.com/greg0ire/doctrine-orm/commit/18366db5789b03e1d8a34933fbbff97a768a9cfe,不再需要“JoinColumns”属性,多个“JoinColumn”属性就足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多