Roger Guasch
Roger Guasch

Reputation: 410

Symofny2 n-m relationship with extra field

I have two tables (test and question) and the middle table (n-m). In this point all works fine. But now, I need to put extra information in the (n-m) table, the order of this question in this test

I need this:

id | test_id | question_id | order
1  |    1    |    1        |  3
2  |    1    |    2        |  2
3  |    1    |    3        |  1
4  |    1    |    4        |  4

All these relationship have made with doctrine annotation...

Test Entity

/**
 * @ORM\ManyToMany(targetEntity="Question", inversedBy="tests")
 */

private $questions;

Question Entity

/**
 * @ORM\ManyToMany(targetEntity="Test", mappedBy="questions"))
 */

private $tests;

Any help will be appreciated

EDIT

Hi again! Thanks a lot to @DonCallisto

my entities at the end:

Test

/**
 * @ORM\OneToMany(targetEntity="RTestQuestion", mappedBy="question")
 */

private $questions;

Question

/**
 * @ORM\OneToMany(targetEntity="RTestQuestion", mappedBy="test"))
 */

private $tests;

My new entity "RTestQuestion"

/**
 * ET\BackendBundle\Entity\RTestQuestion
 * 
 * @ORM\Table(name="rtest_question")
 * @ORM\Entity
 */
class RTestQuestion {

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="questions", cascade={"persist", "remove"})
     */
    private $question;

    /**
     * @ORM\ManyToOne(targetEntity="Test", inversedBy="tests", cascade={"persist", "remove"})
     */
    private $test;

    /**
     * @var integer $order
     *
     * @ORM\Column(name="question_order", type="integer", nullable=true)
     */
    private $question_order;

I had to make two changes:

And, again, thanks to @DonCallisto!

Upvotes: 0

Views: 81

Answers (1)

DonCallisto
DonCallisto

Reputation: 29922

Split the relationship into a 1-n and m-1 as follows

Test Entity --- (1 - m) ---> RTestQuestion Entity <--- (m - 1) --- Question

So your code will be

Test Entity

/**
 * @ORM\OneToMany(targetEntity="RTestQuestion", inversedBy="question")
 */

private $questions;

Question Entity

/**
 * @ORM\OneToMany(targetEntity="RTestQuestion", mappedBy="test"))
 */

private $tests;

RTestQuestion Entity

/**
 * @ORM\ManyToOne(targetEntity="Question", mappedBy="questions"))
 */

private $question;

/**
 * @ORM\ManyToOne(targetEntity="Test", mappedBy="tests"))
 */

private $test;

/**
 * EXTRA ATTRIBUTES HERE
 */

Remember that an association with extra fields isn't an association anymore but a new entity!

Upvotes: 3

Related Questions