用户将设置两个参数$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
答案 0 :(得分:2)
这不是一个很好的做法,但你可以在控制器功能中尝试这样的事情:
$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条件中获取NULL值,因为您无法设置这样的变量。