Symfony add data to object on pre persist

给你一囗甜甜゛ 提交于 2019-12-02 03:57:35

This is a structural error in logic. And the clue is in your question and code.

automatically adds the correct market(s)

And:

        /**
        * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Market")
        * @ORM\JoinColumn(name="market", referencedColumnName="id")
        * @var \AppBundle\Entity\Market
        **/
        private $market;

Are incompatible.

If a document can have many agencies and agencies can have one market then your document must allow for many markets. For example:

DocumentA has Agency1 and Agency2. 

Agency1 has MarketParis.

Agency2 has MarketMarrakesh.

This necessarily means that DocumentA has (Agency1's) MarketParis and (Agency2's) MarketMarrakesh -- many markets.

The question you're asking is a much larger topic than just setting or getting. If you want ONLY one market per document then you'll have to enforce uniqueness among document agencies. For example:

Your form creates DocumentA.

The user tries to set Agency1 (MarketParis) and Agency2 (MarketMarrakesh).
This throws an error because there can be ONLY ONE market.

Or another example:

Your form creates DocumentA

The user tries to set Agency1 (MarketParis) and Agency3 (MarketParis). 
This is successful because the uniqueness of the Document's Market is enforced. 

There are many strategies for this and is a much larger topic than your question.

EDIT

If your cardinality logic is correct (fixing any issues I described above) AND your doctrine annotations include cascading persist in all your entities, which look correct from the code above. The only thing I can think of that would not be working correctly is the "by_reference" attribute of your form. Setting "by_reference" to false in your form, with cascade-persist set in your entity, should persist all entities associated with the form. See the by_reference doc here: http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference

If I understand what you said correctly, I believe Documents should not have a reference to Markets at all. But only references Agency.

A Document will have a ManyToMany relation with Agency and that's it.

Then in Document you can do something like:

public function getMarkets()
{
    $markets = array();
    foreach($this->agencies as $agency) {
        $market = $agency->getMarket();
        $id     = $market->getId();

        // Skip duplicates
        if (isset($markets[id]) {
            continue;
        }

        $markets[$id] = $market;
    }

    return $markets;
}

This looks like wrong approach. It makes more sense to have oneToMany relationship between Market and Agency and oneToMany between Agency and Document.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!