用户将设置两个参数$from和$to,然后使用它们进行查询以获取相关的数据信息。
因此,我希望在模型中访问这些变量,而不是每次在查询中重复它们。
控制器
function index()
{
$this->CompCalculation->from="2013-07-01";
$this->CompCalculation->to="2013-07-01";
pr($this->CompCalculation->find('first'));
}模型
class CompCalculation extends AppModel {
var $name = 'CompCalculations';
var $hasMany = array(
'Leave' => array(
'className' => 'Leave',
'foreignKey' => 'user_id',
'conditions' => array('from >= ' => $from,
'to <= ' => $to
),
),
'Timesheet' => array(
'className' => 'Timesheet',
'foreignKey' => 'user_id',
'conditions' => array('from >= ' => $from,
'to <= ' => $to
),
),
'CompLeave' => array(
'className' => 'CompLeave',
'foreignKey' => 'user_id',
'conditions' => array('from >= ' => $from,
'to <= ' => $to
),
),
'Attendance' => array(
'className' => 'Attendance',
'foreignKey' => 'user_id',
'conditions' => array('from >= ' => $from,
'to <= ' => $to
),
),
);
}我已经尝试过以下解决方案
accessing controller variables in model CakePHP
更新
控制器
function index()
{
$this->CompCalculation->sett('2010-09-09');
}模型
class CompCalculation extends AppModel {
var $name = 'CompCalculations';
public $from='01-01-01';
public $from='11-11-11';
public function sett($fr)
{
echo $this->from;
echo $this->from=$fr;
pr($this->find('first'));
echo $this->from;
}
public function __construct($id = false, $table = null, $ds = null) {
$this->hasMany =array(
'Leave' => array(
'className' => 'Leave',
'foreignKey' => 'user_id',
'conditions' => array('STR_TO_DATE(Leafe.from,"%W %d %M %Y") >= ' => $this->from,
'STR_TO_DATE(Leafe.to,"%W %d %M %Y") <= ' => $this->to
),
),
'Timesheet' => array(
'className' => 'Timesheet',
'foreignKey' => 'user_id',
'conditions' => array('STR_TO_DATE(from_date,"%b %d,%Y") >= ' => $this->from,
'STR_TO_DATE(from_date,"%b %d,%Y") <= ' => $this->to
),
),
'CompLeave' => array(
'className' => 'CompLeave',
'foreignKey' => 'user_id',
),
'Attendance' => array(
'className' => 'Attendance',
'foreignKey' => 'user_id',
),
);
parent::__construct($id, $table, $ds);
}
}结果
01-01-01
2010-09-09
SQL转储使用01-01-01显示查询(而不是2010-09-09)
2010-09-09
发布于 2013-08-19 13:17:15
这不是一个很好的实践,但是您可以在控制器函数中尝试这样的方法:
$this->CompCalculation->hasMany['Timesheet']['conditions']=
array('STR_TO_DATE(Timesheet.from_date,"%b %d,%Y") >= ' =>
'2013-06-01','STR_TO_DATE(Timesheet.from_date,"%b %d,%Y") <= ' =>
'2013-07-01');
$this->CompCalculation->hasMany['Leave']['conditions']=
array('STR_TO_DATE(Leave.from,"%W %d %M %Y") >= ' =>
'2013-06-01','STR_TO_DATE(Leave.to,"%W %d %M %Y") <= ' => '2013-07-01');其他人也是如此。
通过这样做,您将在控制器中设置条件并将其传递给模型。否则,您必须在SQL条件下获得空值,同时尝试在模型中设置变量,因为您不能这样设置变量。
https://stackoverflow.com/questions/18312246
复制相似问题