【发布时间】:2013-12-23 09:15:34
【问题描述】:
我正忙于 CakePHP 的发票项目。我已经在模型中设置了我的相关表,但不知何故它没有转发到视图。
这些是我的模型:
发票模型
class Invoice extends AppModel {
public $hasOne = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'id'
),
'Project' => array(
'className' => 'Project',
'foreignKey' => 'id'
),
);
...
项目模型
class Project extends AppModel {
public $hasOne = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'id'
)
);
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
'foreignKey' => 'project_id'
),
);
客户模型
class Customer extends AppModel {
public $virtualFields = array(
'full_name' => 'CONCAT(Customer.frontname, " ", Customer.lastname)',
'display_name' => 'IF(Customer.company > " ", Customer.company, CONCAT(Customer.frontname, " ", Customer.lastname))',
);
public $hasMany = array(
'Project' => array(
'className' => 'Project',
'foreignKey' => 'customer_id',
),
'Invoice' => array(
'className' => 'Invoice',
'foreignKey' => 'customer_id',
),
);
还有观点:
<?php
foreach($invoices as $invoice){
?>
<td><?php echo $invoice['Customer']['display_name']; ?></td>
<td><?php echo $invoice['Project']['project_name']; ?></td>
这是我的控制器:
<?php
class InvoicesController extends AppController {
public $helpers = array('Status');
public function index() {
$uid = $this->Auth->user('cloud_id');
$this->set('uid', $uid);
$allInvoices = $this->Invoice->find('all', array(
'conditions' => array(
'Invoice.cloud_id' => $this->Auth->user('cloud_id'),
)
)
);
$this->set('invoices', $allInvoices);
}
如果我打印发票,我可以看到相关字段,但值是空的。像这样:
Array
(
[Invoice] => Array
(
[id] => 143
[cloud_id] => 1
[invoice_number] => 143
[customer_id] => 2
[date] => 2013-08-17
[period] => 30
[project_id] => 1
[status] => 1
[notes] =>
[secret] => df56cd45ea7cb086458cc5c3480f77c386647a86
)
[Customer] => Array
(
[id] =>
[cloud_id] =>
[company] =>
[frontname] =>
[lastname] =>
[address] =>
但是如果我更改模型中的外键,我会收到该列不存在的错误。
这里出了什么问题?
提前谢谢你。
【问题讨论】:
-
控制器在哪里?
-
那些关系是错误的。尝试将您的模型与 条件 联系起来,并将
foreignKey设置为 false。你用的是什么版本的蛋糕?除非您专门使用他们推荐的数据库模式(用于外键名称),否则旧版本对于链接模型非常糟糕 -
我已经添加了控制器。我正在使用 2.4.3。
-
查看类似问题的答案:stackoverflow.com/a/20462719/2812842
-
你为什么不检查查询?
标签: php cakephp cakephp-model