Cakephp 虚拟字段作为其他模型字段的别名-SQL:未知列错误
我对一个现有的Cake项目还不熟悉,我们试图在一个模型中使用一个virtualField来别名另一个模型字段。在这方面:Cakephp 虚拟字段作为其他模型字段的别名-SQL:未知列错误,cakephp,cakephp-1.3,cakephp-model,Cakephp,Cakephp 1.3,Cakephp Model,我对一个现有的Cake项目还不熟悉,我们试图在一个模型中使用一个virtualField来别名另一个模型字段。在这方面: class Product extends AppModel { var $name = 'Product'; var $hasOne = array('ProductPrice'); var $virtualFields = array( 'price' => 'ProductPrice.current_price'
class Product extends AppModel {
var $name = 'Product';
var $hasOne = array('ProductPrice');
var $virtualFields = array(
'price' => 'ProductPrice.current_price'
);
// Typical fields in the database for Product. id, name, etc.
}
class ProductPrice extends AppModel {
var $name = 'ProductPrice';
var $belongsTo = array('Product');
// Fields are product_id, current_price
}
ProductPrice模型适用于数据库中的视图,该视图包含不同的价格层,并具有允许检索产品当前价格的current_price列。通过以下方式访问产品模型时:
$this->Product->find('all' ....);
我在获取价格字段方面没有任何问题。问题是,如果对产品的查询是通过以下方式间接完成的
$this->Inventory->find('all');
我们得到:SQL错误:1054:字段列表中的未知列“ProductPrice.current_price”[CORE/cake/libs/model/datasources
/dbo_source.php,第681行]
我知道问题在于库存查询生成的SQL没有尝试加入ProductPrice视图。我假设这将通过产品模型自动实现,因为它知道“hasOne”产品价格
我尝试将库存模型的“递归”设置为2,1等,但没有成功
我错过了什么?TLDR:
不能在中使用来自不同模型的字段
其他选项: 如果您正在执行以下查询:
$this->Inventory->find('all');
您可以使用CakePHP之类的工具来确保获得所需的数据:
//controller code
$inv = $this->Inventory->getInventory();
//model code
class Inventory extends AppModel {
public $actsAs = array('Containable');
public function getInventory() {
return $this->find('all', array(
'contain' => array(
'Product' => array(
'ProductPrice'
)
)
));
}
}
在上面的代码示例中使用containable like应该以如下格式返回数据:
[0] => Array
(
[Inventory] => Array
(
[id] => 12345
)
[Product] => Array
(
[0] => Array
(
[id] => 54321
[title] => product A
)
[ProductPrice] => Array
(
[id] => 6789
[current_price] => 24.99
)
)
//...
当您获得这样的数据时,应该很容易访问产品的当前价格
您也可以在控制器中执行此操作,但更好的做法是将查询保留在模型中,以保持在“胖模型,瘦控制器”的咒语中。如果您真的想将其保存在控制器中,可以执行以下操作:
$inv = $this->find('all', array(
'contain' => array(
'Product' => array(
'ProductPrice'
)
)
);
(但是-您仍然必须指定$actsAs模型是可包含的(根据第一个代码示例)。TLDR:
不能在中使用来自不同模型的字段
其他选项: 如果您正在执行以下查询:
$this->Inventory->find('all');
您可以使用CakePHP之类的工具来确保获得所需的数据:
//controller code
$inv = $this->Inventory->getInventory();
//model code
class Inventory extends AppModel {
public $actsAs = array('Containable');
public function getInventory() {
return $this->find('all', array(
'contain' => array(
'Product' => array(
'ProductPrice'
)
)
));
}
}
在上面的代码示例中使用containable like应该以如下格式返回数据:
[0] => Array
(
[Inventory] => Array
(
[id] => 12345
)
[Product] => Array
(
[0] => Array
(
[id] => 54321
[title] => product A
)
[ProductPrice] => Array
(
[id] => 6789
[current_price] => 24.99
)
)
//...
当您获得这样的数据时,应该很容易访问产品的当前价格
您也可以在控制器中执行此操作,但更好的做法是将查询保留在模型中,以保持在“胖模型,瘦控制器”的咒语中。如果您确实希望将其保留在控制器中,您可以执行以下操作:
$inv = $this->find('all', array(
'contain' => array(
'Product' => array(
'ProductPrice'
)
)
);
(但是-您仍然必须指定$actsAs模型是可包含的(每个第一个代码示例)。感谢您提供的信息。如果有机会,我将尝试实现此功能并提供反馈。感谢您提供的信息。如果有机会,我将尝试实现此功能并提供反馈。