ApiPlatform PUT关联多个实体(注解)
创始人
2024-09-08 02:00:17
0

要使用ApiPlatform PUT关联多个实体,可以使用注解来指定关联实体的属性。以下是一个使用注解的示例解决方法:

假设有两个实体:OrderProduct,一个订单可以包含多个产品。

  1. 首先,在Order实体中添加一个属性来关联产品:
use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Order
{
    // ...

    /**
     * @var Collection|Product[]
     *
     * @ORM\ManyToMany(targetEntity="Product")
     * @ApiProperty(iri="http://schema.org/Product")
     */
    public $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

    // ...
}
  1. 然后,在Product实体中添加一个属性来关联订单:
use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Product
{
    // ...

    /**
     * @var Collection|Order[]
     *
     * @ORM\ManyToMany(targetEntity="Order", mappedBy="products")
     * @ApiProperty(iri="http://schema.org/Order")
     */
    public $orders;

    public function __construct()
    {
        $this->orders = new ArrayCollection();
    }

    // ...
}
  1. 最后,在API资源类中使用PUT方法来关联多个实体:
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ApiResource
 * @ORM\Entity
 */
class Order
{
    // ...
    
    /**
     * @var Collection|Product[]
     * 
     * @ORM\ManyToMany(targetEntity="Product")
     * @ApiProperty(iri="http://schema.org/Product")
     * @ApiSubresource
     */
    public $products;
    
    // ...
}

现在,您可以使用PUT请求来更新订单并关联多个产品。请求的主体应该包含关联产品的标识符列表。例如:

PUT /orders/{orderId}
{
  "products": ["/products/1", "/products/2", "/products/3"]
}

在上面的示例中,订单将与产品1、2和3关联起来。

相关内容

热门资讯

今日头条!微信老友广东辅助器,... 今日头条!微信老友广东辅助器,微乐福建辅助器,安装教程(原来有开挂辅助器)是一款可以让一直输的玩家,...
每日必看推荐!微信小程序家乡大... 每日必看推荐!微信小程序家乡大二辅助工具,新西游辅助器,透视教程(原来有开挂辅助安装);1、选手技艺...
玩家亲测!广东插件智能插件安装... 玩家亲测!广东插件智能插件安装包免费,wepoker轻量版有透视吗,详细教程(原来有开挂辅助挂);广...
重大通报!哈糖大菠萝开挂,we... 重大通报!哈糖大菠萝开挂,we-poker是什么软件,解密教程(原来有开挂辅助助手);1.哈糖大菠萝...
解密关于!鱼乐达人辅助修改器,... 解密关于!鱼乐达人辅助修改器,下载微乐小程序自建房透视,介绍教程(原来有开挂辅助软件);解密关于!鱼...
重大发现!四川家园游戏辅助,微... 重大发现!四川家园游戏辅助,微乐自建房辅助多少钱一个月,AI教程(原来有开挂辅助器);微乐自建房辅助...
玩家必用!玉海楼茶苑怎么开挂,... 玩家必用!玉海楼茶苑怎么开挂,天酷互娱有辅助工具嘛,黑科技教程(原来有开挂辅助插件);天酷互娱有辅助...
一分钟教你!椰岛常胜游戏破解,... 一分钟教你!椰岛常胜游戏破解,广东雀神透视,解密教程(原来有开挂辅助下载);椰岛常胜游戏破解软件透明...
实测发现!三江互娱辅助,wpk... 实测发现!三江互娱辅助,wpk显示有透视挂,详细教程(原来有开挂辅助助手),三江互娱辅助是用手机号来...
程序员教你!长春科乐第三方辅助... 程序员教你!长春科乐第三方辅助工具,wepoker代打辅助机器人,曝光教程(原来有开挂辅助黑科技);...