每个订单都有'from_str'和'from_bldg'字段。在Order模型中,我创建了连接以下字段的虚拟字段"from":
public $virtualFields = array(
'from' => 'CONCAT(Order.from_str, " ", Order.from_bldg)'
);
但是,Order也有一个到Company的链接。因此,如果字段from_company_id不是0/null,我希望在Order中的"from"字段中显示公司名称。
例如:Order1有from_str = "Baker st"
、from_bld = "221B"
和from_company_id = "0"
Order2有from_str
和from_bld null
,但from_company_id = "1"
id = 1的公司名称为"Sun, Inc."
因此,对于Order1的"from"字段,我希望有"Baker st 221B",
对于Order2的"from"字段,我希望得到"Sun, Inc."。
要实现这一点,模型或控制器的代码看起来像什么?
您将需要创建两个模型之间的关系。由于您没有根据CakePHP约定(即company_id
)命名外键,因此您必须自己指定。
app/模型/Order.php
class Order extends AppModel {
public $belongsTo = array(
'Company' => array(
'foreignKey' => 'from_company_id',
)
);
}
app/模型/Company.php
class Company extends AppModel {
public $hasMany = array(
'Order' => array(
'foreignKey' => 'from_company_id',
)
);
}
在你的控制器中;
$order = $this->Order->find('first, array(
'conditions' => array(
'Order.id' => $id, // or whatever name the ID has
),
'recursive' => 1,
));
debug($order);
这会给你Order和'Company'的详细信息。然而, 公司详细信息将在$order
数组内的单独'键' (' company ')中。如果这只是为了在视图中输出订单,我不认为有理由使用virtualField将数据合并到数组中的' order '键。
如果合并数据到相同的键是一个重要的要求,请描述您的要求,然后我可以帮助你进一步