我有两个表,即“客户”和“事件”。两者的关系如下:
事件
var $belongsTo = array(
...
'Customer'=>array(
'className' => 'Customer',
'foreignKey' => 'customer_id'
)
);
客户
var $hasMany = array(
'Event' => array(
'className' => 'Event',
'foreignKey' => 'customer_id',
'dependent' => false,
)
);
每条客户记录都包含一个公司 ID 以及当前登录的用户。我想要实现的是获取一天的所有事件,仅与特定公司相关,但这当然行不通,因为事件表不包含公司 ID。也许以下查找调用将有助于更好地理解问题:
$conditions = array('company_id'=>CakeSession::read("Auth.User.company_id"), 'date'=>date("Y-m-d", $tomorrow));
$tomorrowsEvents = $this->find('all', array(
'conditions'=>$conditions, 'contain'=>array('User', 'Customer')));
另外,一个客户属于一个公司,一个公司有很多客户,如下:
客户
var $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id',
'dependent' => false,
),
);
公司
var $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'company_id',
'dependent' => false
),
'Customer'=>array(
'className' => 'Customer',
'foreignKey' => 'company_id',
'dependent' => false
)
);
非常感谢任何帮助。
最佳答案
实际上,我会通过从客户那里执行此查询来“向后”执行此查询,并使用可包含的行为来包含相关的事件:
$this->Customer->find('all',
array(
'conditions' => array(
'company_id' => CakeSession::read("Auth.User.company_id")
),
'contain' => array(
'Event' => array(
'conditions' => array(
'Event.date' => date("Y-m-d", $tomorrow)
)
)
)
));
关于mysql - 数据库索引 cakePHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22663143/