CakePHP 3.0保存了belongsToMany数据问题

时间:2015-01-18 17:37:00

标签: cakephp cakephp-3.0

我在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);
    }
}

正如我们所看到的,我正在尝试保存附加Call的{​​{1}},导致问题的部分是我还要尝试附加{{ {1}}要将Order的ID保存到连接表。如果我删除了产品ID,则ProductsOrder会成功保存。

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

1 个答案:

答案 0 :(得分:3)

您无法使用_ids密钥进行保存,您需要具有相应主键值的实体。

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

长话短说,不要手动创建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);

另见