How to make Bidirectional OneToMany relationship with JoinTable in Doctrine? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Wednesday, June 23, 2021

How to make Bidirectional OneToMany relationship with JoinTable in Doctrine?

I have read the official docs and many questions here. I also tried blindly few things without results. Please do not focus on "why I need it" but whether this is possible:

I have these 2 entities:


/**
 * @ORM\Entity
 */
class Payout
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id;
    
    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\BalanceLog")
     * @ORM\JoinTable(name="payouts_balance_logs",
     *      joinColumns={@ORM\JoinColumn(name="payout_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="balance_log_id", referencedColumnName="id", unique=true)}
     *      )
     */
    private Collection $balance_logs;

}


/**
 * @ORM\Entity
 */
class BalanceLog
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Payout")
     */
    private ?Payout $payout;

}

One BalanceLog CAN (but does not have to) point to a Payout. And every Payout has at least one BalanceLog. This all is achieved with payouts_balance_logs table, where balance_log_id is unique (meaning a single balance log can point to only one payout)

I can easily make a bi-directional ManyToMany relationship, but then I have BalanceLog::$payouts collection, not a single object.

I can also make it bi-directional OneToMany/ManyToOne without using JoinTable, but then EVERY BalanceLog will need its nullable payout_id column.

I think that what I want has to be common and achievable. Please help, thanks!



source https://stackoverflow.com/questions/68088844/how-to-make-bidirectional-onetomany-relationship-with-jointable-in-doctrine

No comments:

Post a Comment