【问题标题】:Persisting related entities in Symfony correctly (Foreign Keys)在 Symfony 中正确保存相关实体(外键)
【发布时间】:2014-05-20 03:35:01
【问题描述】:

我有两个对象:Company 和 Location

一家公司可以有许多地点(比如代表他们在其中设有办事处的每个城市)。

我已经设置模型/实体来表示这种关系:

Location: id, address, company
Company: id, name, locations

所以我在公司上有自动生成的功能:

public function addLocation(Location $locations)
{
    $this->locations[] = $locations;
    return $this;
}

我的问题是,如果我想将新公司和新地点都添加到我的数据库中 - 我可以通过添加到公司中的地点来完成吗? Symfony 会足够聪明地找出所有外键 ID 吗?

说我要创建:

$company = new Company();
$company->setName('NEW COMPANY');

$location1 = new Location();
$location1.setAddress('123 Fake St');
// $location1.setCompany($company) // Is this required?

$location2 = new Location();
$location2.setAddress('456 Test Hwy');
// $location2.setCompany($company) // Is this required?

$company->addLocation($location1);
$company->addLocation($location2);

我很好奇这是如何工作的,或者我是否找错了树,应该只在一次交易中添加公司,然后再添加位置。任何想法表示赞赏 - 谢谢。

【问题讨论】:

    标签: php entity-framework symfony doctrine


    【解决方案1】:

    你可以这样做:

    <?php
    
    /** @Entity */
    class Company
    {
        // ...
    
        /**
         * @ManyToMany(targetEntity="Location", inversedBy="companies")
         * @JoinTable(name="company_location")
         */
        private $locations;
    
        public function __construct() {
            $this->locations = new \Doctrine\Common\Collections\ArrayCollection();
        }
    
        // ...
    }
    
    /** @Entity */
    class Location
    {
        // ...
        /**
         * @ManyToMany(targetEntity="Company", mappedBy="locations")
         */
        private $companies;
    
        public function __construct() {
            $this->companies = new \Doctrine\Common\Collections\ArrayCollection();
        }
    
        // ...
    }
    

    我认为您正在寻找级联持久化,请在此处阅读更多信息:Doctrine 2 ManyToMany cascade

    【讨论】:

    • 是的。级联/持久是我需要添加的注释 - 然后它起作用了:) 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多