Codeigniter Datamapper ORM生成错误的查询

时间:2013-01-17 14:26:42

标签: php sql codeigniter codeigniter-datamapper

我第一次使用Datamapper ORM以及CRUD的数组 htmlforms 扩展。到目前为止,这两个扩展都适用于我的所有模型,但今天我面临着一个模型的奇怪问题。

当我尝试保存对象时,我收到了这个SQL错误:

A Database Error Occurred
Error Number: 1054
Unknown Column 'orderitems.orderitem_id' in where clause

SELECT COUNT(*) AS `numrows` FROM (`orderitems`) WHERE `orderitems`.`order_id` = 2 AND `orderitems`.`orderitem_id` NOT IN (8, 9)

Filename: libraries/datamapper.php
Line Number: 2526

我认为正确的SQL应该是 ... AND orderitemsid NOT IN(...)因为Orderitem模型引用自身而不是另一个相关的模型。此错误在count()方法内触发,该方法由save()方法触发,该方法由数组 DM扩展的from_array()方法触发。

这是我的控制器代码

//Get order
$order = new Order(2);

//Fields to render in the form
$fields = array('orderitem');

//Save changes from $_POST
if($post = $this->input->post())
{
$order->trans_begin();
if ( ! $order->from_array($post, $fields, TRUE) OR $order->trans_status() === FALSE)
$order->trans_rollback();
else
$order->trans_commit();
}

//Load view
$data = array(
'order' => $order,
'fields'=> $fields,
);
$this->load->view('order/edit', $data);

这是我的观看代码

echo $order->render_form($fields);

以下是隐含的模型

class Order extends DataMapper {
public $has_one = array('orderstatus', 'place', 'user', 'paymenttype');
public $has_many = array('orderitem');
...
/*SQL:
CREATE TABLE IF NOT EXISTS orders (
id mediumint(4) unsigned NOT NULL auto_increment PRIMARY KEY,
user_id mediumint(1) unsigned, FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE RESTRICT,
orderstatus_id tinyint(1) unsigned, FOREIGN KEY (orderstatus_id) REFERENCES orderstatuses(id) ON UPDATE CASCADE ON DELETE RESTRICT,
place_id tinyint(1) unsigned, FOREIGN KEY (place_id) REFERENCES places(id) ON UPDATE CASCADE ON DELETE SET NULL,
paymenttype_id tinyint(1) unsigned, FOREIGN KEY (paymenttype_id) REFERENCES paymenttypes(id) ON UPDATE CASCADE ON DELETE SET NULL,
total float NOT NULL DEFAULT 0
) ENGINE = InnoDB;
*/

class Orderitem extends DataMapper {
public $has_one = array('order', 'orderitemstatus');
public $has_many = array('orderitemextra');
...
/*SQL:
CREATE TABLE IF NOT EXISTS orderitems (
id int(1) unsigned NOT NULL auto_increment PRIMARY KEY,
order_id mediumint(1) unsigned, FOREIGN KEY (order_id) REFERENCES orders(id) ON UPDATE CASCADE ON DELETE CASCADE,
orderitemstatus_id tinyint(1) unsigned, FOREIGN KEY (orderitemstatus_id) REFERENCES orderitemstatuses(id) ON UPDATE CASCADE ON DELETE RESTRICT,
name varchar(128) NOT NULL,
price float NOT NULL,
) ENGINE = InnoDB;
*/

正如我所说,我对其他型号没有任何问题,因此我不知道这是DM问题还是我的代码或我的任何模型定义的问题。

我会感激任何帮助。

谢谢!

0 个答案:

没有答案