CakePHP 3.0保存belongsToMany数据问题

CakePHP 3.0 saving belongsToMany data problems

我在 belongsToMany 关联中保存数据时遇到问题。这是我收到的错误:

Fatal Error (1): Call to a member function get() on a non-object in [application/vendor/cakephp/cakephp/src/ORM/Association/BelongsToMany.php, line 854]

这是导致问题的代码段:

public function add(){
    $session = $this->request->session();
    $call = $this->Calls->newEntity([
        "user_id" => $this->Auth->user("id"),
        "customer_id" => $session->read("Customer.id"),
        "comment" => $this->request->data["comment"],
        "result_id" => $this->request->data["result_id"]
    ]);
    if($this->request->data["result_id"] === 0){
        $deliveryMode = $this->request->data["order"]["delivery"]["mode"];
        $order = new Order([
            "delivery" => $deliveryMode,
            "products" => [
                "_ids" => [1, 2]
            ]
        ]);

        if($deliveryMode === 1){
            $order->set("smartpost_delivery_id", $this->request->data["order"]["delivery"]["locations"][1]["id"]);
        }

        $call->order = $order;
    }
    $result = $this->Calls->save($call);
    if($result){
        $session->write("Customer.id", null);
        echo json_encode(["id" => $result->id]);
    } else{
        echo json_encode($call->errors());
        $this->response->statusCode(400);
    }
}

正如我们所看到的,我正在尝试保存附加了 OrderCall,造成问题的部分是我还试图附加一个列表Products 个 ID 到 Order 以保存到连接 table。如果我删除产品 ID,CallOrder 会成功保存。

4 table 涉及:callsordersproductsorders_productsHere's a visual representation of the tables。 table 个对象的代码已由蛋糕应用程序自动烘焙。如果需要,我可以为他们提供代码。关联:Calls hasOne OrderOrders belongsToMany Products

您不能使用 _ids 键保存,您需要具有适当主键值的实体。

特殊的 _ids 键是一种方便的格式,由编组器在将数据转换为实体时处理。它将从数据源中获取适当的数据并将关联 属性 替换为实体列表。

长话短说,不要手动创建 Order 实体,让编组器来做。无论如何,您可能都不想这样做,因为您将用户数据插入实体中,实体应该首先 validated,这就是为什么您还应该在将数据转换为 smartpost_delivery_id 值之前将其添加到数据中一个实体:

$orderData = [
    "delivery" => $deliveryMode,
    "products" => [
        "_ids" => [1, 2]
    ]
];

if($deliveryMode === 1) {
    $orderData["smartpost_delivery_id"] =
        $this->request->data["order"]["delivery"]["locations"][1]["id"];
}

// Adjust the name of the association in case necessary
$order = $this->Calls->association('Orders')->newEntity($orderData);

另见