带有php属性的JoinColumns/组合键

whlutmcx  于 2023-01-08  发布在  PHP
关注(0)|答案(2)|浏览(153)

如何用PHP属性声明joinColumns/组合键。还没有找到正确的方法,也没有文档(https://www.doctrine-project.org/projects/doctrine-orm/en/2.11/reference/attributes-reference.html
实体
Comment.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;

}
jmo0nnb3

jmo0nnb31#

我今天遇到了同样的问题,并设法找到了一个解决方法。看起来JoinColumns确实不能作为PHP 8属性使用,至少在Doctrine ORM 2.11和即将到来的2.12 / 3.0中都不能使用。
但是,您可以通过将连接列定义移动到类级别的AssociationsOverride属性中来解决此问题,如下所示:

#[ORM\Entity(repositoryClass: CommentRepository::class)]
#[ORM\AssociationOverrides([
    new ORM\AssociationOverride(
        name: 'pullRequest',
        joinColumns: [
            new ORM\JoinColumn(name: 'pull_request_id', referencedColumnName: 'id'),
            new ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'repo_id')
        ]
    )
])]
class Comment
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: PullRequest::class, inversedBy: 'comments')]
    private $pullRequest;
}
tf7tbtn2

tf7tbtn22#

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

相关问题