接收与Doctrine2和Symfony2的多对多关系的实体

时间:2017-08-01 08:51:55

标签: php symfony doctrine-orm

我有两个实体:

致电实体:

/**
 * @ORM\Table(
 *        name="calls",
 * )
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repositories\CallRepository")
 */
class Call implements \JsonSerializable
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    public $id;

    /**
     * @var User
     * @ORM\ManyToOne(targetEntity="User", cascade={"all"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="cascade")
     */
    public $user;

    /**
     * Many Calls have Many Tags.
     * @ORM\ManyToMany(targetEntity="Tag", mappedBy="taggedCalls", fetch="EAGER")
     */
    public $tags;

    /**
     * @var string
     * @ORM\Column(type="string", length=40, nullable=false)
     */
    public $phone;

    public function __construct(User $user)
    {
        $this->user = $user;
        $this->tags = new ArrayCollection();
    }

    public function jsonSerialize()
    {
        $call = [
            'id' => $this->id,
            'phone' => $this->phone,
            'tags' => [],
        ];

        foreach ($this->tags as $tag) {
            $author['books'][] = $tag->jsonSerialize();
        }

        return $call;
    }

    /**
     * @return ArrayCollection|Tag[]
     */
    public function getTags()
    {
        return $this->tags;
    }

    public function addNewTag($tag)
    {
        if ($this->tags->contains($tag)) return;
        $this->tags[] = $tag;
    }

}

标记实体:

/**
 * @ORM\Table(name="tags",
 *     uniqueConstraints={@ORM\UniqueConstraint(name="tag_value", columns={"value"})})
 * @ORM\Entity()
 */
class Tag implements \JsonSerializable
{

    /**
     * @var integer
     *
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    public $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=120, nullable=false)
     */
    public $value;

    /**
     * @ORM\ManyToMany(targetEntity="Call", inversedBy="tags")
     * @ORM\JoinTable(name="calls_tags",
     *      joinColumns={@ORM\JoinColumn(name="call_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id")}
     *      )
     */
    private $taggedCalls;


    public function __construct($value)
    {
        $this->color = $color;
    }


    public function getId()
    {
        return $this->id;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValue($value)
    {
        $this->value = $value;
    }


    function jsonSerialize()
    {
        return [
            'id' => $this->id,
            'value' => $this->value,
        ];
    }
}

REST控制器,用于接收具有相应标记数组的Call个实体数组:

   /**
 * @Route("/calls", name="my_v1_calls")
 * @Method("GET")
 */
public function calls(Request $request)
{
    $this->recordLog($request);
    $user = $this->authorizeUser($request);

    $qb = $this->callRepository->createQueryBuilder('c');
    $qb->where("c.user = :user")->setParameter("user", $user);

    $limit = $request->query->get("limit", 500);
    if ($limit < 1 || $limit > 500)
        $limit = 500;

    $qb->setMaxResults($limit);

    $calls = $qb->getQuery()->getResult();

    $serializedCalls = [];
    foreach ($calls as $call) {
        $serializedCalls[] = $call->jsonSerialize();
    }

    return new JsonResponse(array(
        'calls' => $serializedCalls
    ));
}

表连接工作正常:添加新标签会在calls_tags表中创建有效关系。但是我无法接收相应调用的标记:上面显示的控制器代码片段为每个调用返回空标记数组,即使数据表中的数据存在且有效。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您认为这部分代码会做什么?

public function jsonSerialize()
{
    $call = [
        'id' => $this->id,
        'phone' => $this->phone,
        'tags' => [],
    ];

    foreach ($this->tags as $tag) {
→       $author['books'][] = $tag->jsonSerialize();
    }

    return $call;
}

如果关联实体实现JsonSerializable,您只需执行此操作:

public function jsonSerialize()
{
    return [
        'id' => $this->id,
        'phone' => $this->phone,
        'tags' => $this->tags->toArray(),
    ];
}