【问题标题】:Model "CartItem" is not associated with model "Product" but it is?模型“CartItem”与模型“产品”没有关联,但它是?
【发布时间】:2013-07-22 01:25:52
【问题描述】:

我正在编写一个 CakePHP 插件。在我的插件AppModel 中,我有:

public $actsAs = array(
    'Containable'
);

然后我有两个模型:CartItemProduct。我的CartItem 模型如下所示:

<?php
class CartItem extends ShoppingCartAppModel {

    public $belongsTo = array(
        'Cart',
        'Product'
    );
}

但是,在我的控制器中调用 Cart 模型时,我收到以下错误:

警告 (512):模型“CartItem”与模型“产品”不关联 [CORE/Cake/Model/Behavior/ContainableBehavior.php,第 344 行]

为什么会这样,当我定义我的 CartItem 模型通过 belongsTo 关联与 Product 模型关联时?

编辑:我已将我的问题缩小到我试图在我的 Cart 模型中获取我的购物车及其内容的地方。这是电话:

public function findBySessionId($sessionId) {
    $cart = $this->find('first', array(
        'conditions' => array(
            'Cart.session_id' => $sessionId
        ),
        'contain' => array(
            'CartItem' => array(
                'Product'
            )
        )
    ));
    return $cart;
}

【问题讨论】:

  • 如果你只使用 $this->find 这样的方式,它是否真的在使用你的模型文件?你不需要 $this->CartItem->find 否则它只会使用通用的 appModel 类?!
  • 在我的CartController 中,我希望能够获取用户的购物车,以及该购物车中的CartItems 和相关的Products,以便我可以将其显示给用户。

标签: cakephp cakephp-model


【解决方案1】:

模型关联需要插件前缀

从问题来看,购物车模型很可能是这样定义的:

    public $hasMany = array(
        'CartItem'
    );
}

这意味着 Cake 期待以下内容:

app
    Model
        CartItem.php <- 'CartItem' means the model is in the App, not a plugin
    Plugin
        Model
            Cart.php

App CartItem 模型不存在,因此将是 AppModel 的一个实例。

在定义模型关联时,始终确保使用插件前缀(如果适用):

    public $hasMany = array(
        'ShoppingCart.CartItem' // Load the model from this same plugin
    );
}

【讨论】:

  • 我正在尝试从我的 Cart 模型加载 CartItems(和相关的 Products)。我将使用示例调用更新我的问题。
  • 那么我该如何解决它,以便我可以从Cart 访问每个CartItemProduct?在使用 Containable 行为之前,我没有遇到过这个问题。
  • 它是AppModel,但我确定我的模型命名正确:CartItem.php。是因为它在插件中而不是“主”应用程序中吗?
  • 嗯,这是“模型文件名称错误”的不同排列,我已经更新了答案
  • 我是这么想的,但是当我添加 ShoppingCart. 前缀时,我得到一个 SQL 错误:Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`CartItem` WHERE `ShoppingCart`.`CartItem`.cart_id = (2)' at line 1
【解决方案2】:

找出问题所在。插件中的模型需要类名中的插件名。

例如:

<?php
class Cart {

    public $hasMany = array(
        'CartItem' => array(
            'className' => 'ShoppingCart.CartItem'
        )
    );
}

仅在关联名称中指定插件名称对我来说会导致 SQL 错误,因此您可以通过手动指定类名称(带有插件前缀)来规避。

【讨论】:

  • Specifying the plugin name just in the association name - 如果你的意思是数组键,它是关联别名 - 并且将 . 放入其中只会造成一般混乱。简写语法 ($hasMany =&gt; array('Plugin.Model')) 等同于完整语法 ($hasMany =&gt; array('Model' =&gt; array('className' =&gt; 'Plugin.Model')) - 还有更多关于 in the documentation 的内容。无论如何,尽管很高兴您找到了问题的解决方案。
  • 是的。就像我说的,当我将插件名称放在数组键/关联别名中时,它触发了 SQL 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多