Doctrine ORM join entity via many to one table

by Angelo   Last Updated March 24, 2019 21:26 PM

I have these entities in Symfony 3.4:

class Status {

    /*
     * @var int
     */   
    public $id;

    /*
     * @var string
     */
    public $name;

    /*
     * @var StatusLabel $label
     *
     * @ManyToOne(targetEntity="StatusLabel")
     * @JoinColumn(name="statusLabelId", referencedColumnName="id")
     */
    public $label;

    /*
     * @return StatusLabel
     */
    public function getLabel($activity) // Needs an activity as an argument 
    {
        return $this->label;
    }
}

class Activity {

    /*
     * @var int
     */   
    public $id;

    /*
     * @var string
     */
    public $name;

}

class StatusLabel {

    /*
     * @var int
     */   
    public $id;

    /*
     * @var int
     */
    public $statusId;

    /*
     * @var int
     */
    public $activityId;

    /*
     * @return string
     */
    public $label;

}

The new entity, which allows us to set a label for Status, unique to a status, activity is called StatusLabel. The tables have the following attributes:

Status
--------
| id | name |
StatusLabel
--------
| id | activityId | statusId | label |
Activity
--------
| id | name |

Trying to use annotations to state the join, so that I can get the StatusLabel.label if I have activity, for example:

$activity = $this->getDoctrine()->getRepository('Entity\Activity')->findOneBy(['slug' => 'outdoors-activity']);
/** @var StatusLabel $activityStatusLabel */
$activityStatusLabel = $userActivity->getStatus()->getLabel($activity); 
echo $activityStatusLabel->getLabel();

It would be better for the activity to be passed in automatically, but I cannot figure out how to do this with ORM annotations. I don't want to query from the entity!



Related Questions


Updated March 18, 2019 09:26 AM

Updated April 19, 2019 13:26 PM

Updated February 28, 2019 08:26 AM

Updated June 12, 2017 16:26 PM