It happens that I have a table where I keep records of things that are going to be done at a certain date and time, where I have the attributes: id, task, StartDate, EndDate.
What I want is that no other task can be recorded within an already assigned schedule. I have validated so that the end date is not less than the start date, as well as that the start date is not greater than the end date. Try to add a unique rule, which when selecting a start or end date that exists in the database, an error message is displayed indicating that you have to select another time. It works only when selecting the exact date but if I select another hour or minute within the schedule (start and end), it doesn't show an error message. Example:
Start: 10/11/2021 1:20 PM - End: 10/11/2021 3:20 PM
By selecting 10/11/2021 1:20 PM - Assigned Schedule.
By selecting 11/10/2021 13:21 - Validate as ok.
...
... same message when selecting any time within the range.
...
By selecting 10/11/2021 3:20 PM - Assigned Schedule.
Rules
public function rules()
{
return [
[['task', 'start_date', 'end_date'], 'required'],
[['start_date', 'end_date'], 'default', 'value' => function () {
return date(DATE_ISO8601);
}],
[['start_date', 'end_date'], 'filter', 'filter' => 'strtotime', 'skipOnEmpty' => true],
[['start_date', 'end_date'], 'integer'],
['start_date', 'unique', 'targetClass' => Task::class, 'filter' => function ($query) {
if (!$this->isNewRecord) {
$query->andWhere(['not', ['start_date' => $this->start_date]]);
}
}, 'message'=>'There is an assigned schedule, select another date and time'],
['end_date', 'unique', 'targetClass' => Task::class, 'filter' => function ($query) {
if (!$this->isNewRecord) {
$query->andWhere(['not', ['end_date' => $this->end_date]]);
}
}, 'message'=>'There is an assigned schedule, select another date and time'],
['start_date','compare','compareAttribute'=>'end_date','operator'=>'<','message'=>'Please give correct Start and End dates'],
['end_date','compare','compareAttribute'=>'start_date','operator'=>'>','message'=>'Please give correct Start and End dates.'],
[['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['created_by' => 'id']],
[['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['updated_by' => 'id']],
];
}
I tried to add a between but it did not work for me, I hope you can guide me with this problem.
$query = $this->find()->andFilterWhere(['between', 'start_date', $this->start_date, $this->end_date]);
updated
The sql query that I show performs what I need, but I want to know if it is correct and how I could integrate it through the rules?
SELECT * FROM tbl_task
WHERE start_date_select BETWEEN start_date AND end_date
OR end_date_select BETWEEN start_date AND end_date