【发布时间】:2016-07-22 19:59:58
【问题描述】:
几年前,我使用 CakePHP 2.2 开发了一些东西。在我的Bill 模型中,我有一个virtualField,它计算给定的账单是否已经“完成”:
scheduled_payment = 1
&& (payed_beihilfe IS NOT NULL && payed_beihilfe > 0)
&& (payed_pkv IS NOT NULL && payed_pkv > 0)
这一直很好,直到出现payed_beihilfe 始终为零的情况,因为这部分不再扮演任何角色。有关分布的信息在字段Person.beihilfe_part 中,范围从 0 到 100。如果是极端之一,我不想考虑那里的数量。所以我首先尝试了这个:
scheduled_payment = 1
&& ((payed_beihilfe IS NOT NULL && payed_beihilfe > 0) || Person.beihilfe_part = 0)
&& ((payed_pkv IS NOT NULL && payed_pkv > 0) || Person.beihilfe_part = 100)
当您查看单个 Bill 对象时,此方法有效。但是,只要查看Person,我就会得到are mentioned in the manual 的SQL 错误。基本上这说明不能拥有需要JOIN 操作的virtualFields。这真是太糟糕了,因为我真的需要扩展我拥有的这个“完成”属性。
这是我的Bill 班级:
class Bill extends AppModel {
public $displayField = 'amount';
public $virtualFields = array(
# XXX There is a limitation in the `virtualFields` that it cannot
# use any sort of `JOIN`. Therefore I have to make due with the
# data that is available in the `bills` table. This is a real
# kludge but it seems to work.
"done" =>
"scheduled_payment = 1
&& ((payed_beihilfe IS NOT NULL && payed_beihilfe > 0) || (person_id = 7 && date > '2016-06-01'))
&& (payed_pkv IS NOT NULL && payed_pkv > 0)"
);
public $validate = array(
'amount' => array(
"rule" => array("comparison", ">", 0),
"message" => "Der Rechnungsbetrag muss größer als € 0 sein."
)
);
public $belongsTo = array(
'Doctor' => array(
'className' => 'Doctor',
'foreignKey' => 'doctor_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Person' => array(
'className' => 'Person',
'foreignKey' => 'person_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
这是Person 型号:
class Person extends AppModel {
public $displayField = 'name';
public $hasMany = array(
'Bill' => array(
'className' => 'Bill',
'foreignKey' => 'person_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
查询发生在例如PeopleController::view 函数中:
public function view($id = null) {
$this->Person->id = $id;
if (!$this->Person->exists()) {
throw new NotFoundException(__('Invalid person'));
}
$this->set('person', $this->Person->read(null, $id));
}
这也将引入相关的Bill 对象,并在那里崩溃,因为Person 表不是JOINed 进入获取与给定Person 相关的Bill 对象的查询。这在 CakePHP 中隐式发生,我只是使用了脚手架。
我已经有很长一段时间没有使用 CakePHP 了,因为我大部分时间都远离了 Web 开发。在一个非常小的 Django 项目中,我看到 SQL 表中的行被实例化为真正的 Python 对象。在那里添加一个函数或字段真的很容易。在 CakePHP 中,一切都只是存储在关联数组中。因此,我真的不知道如何添加一个复杂的函数来计算这个“完成”属性。
什么是明智的做法?
【问题讨论】:
-
Person模型与Bill模型的关联究竟如何?您究竟是如何查询Bill模型的? -
我添加了应该回答您问题的代码。票据和人之间存在一对多的关系。使用
Person->read时,CakePHP 会自动进行查询。
标签: cakephp cakephp-2.2