Issue
Is beforeSave()
supposed to be called during seeding?
The beforeSave()
method in my model table currently gets called when I go through the app (in both edit and add), as intended fields get updated after the form submission.
However, when I seed the database after truncating the table, these same fields remain at their default value.
Seed:
public function run()
{
$data = [
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-01', 'game_type_id'=>2, 'user_pt'=>1, 'opponent'=>'Vancouver', 'opponent_pt'=>2, 'is_decision'=>1, 'mins'=>60, 'ga'=>2, 'sog'=>24],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-02', 'game_type_id'=>2, 'user_pt'=>2, 'opponent'=>'Vancouver', 'opponent_pt'=>1, 'is_decision'=>1, 'mins'=>59, 'secs'=>45, 'ga'=>1, 'sog'=>27],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-03', 'game_type_id'=>2, 'user_pt'=>4, 'opponent'=>'Vancouver', 'opponent_pt'=>1, 'is_decision'=>1, 'mins'=>60, 'ga'=>1, 'sog'=>19],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-04', 'game_type_id'=>2, 'user_pt'=>5, 'opponent'=>'Edmonton', 'opponent_pt'=>2, 'is_decision'=>1, 'mins'=>58, 'secs'=>24, 'ga'=>1, 'sog'=>19],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-05', 'game_type_id'=>2, 'user_pt'=>3, 'opponent'=>'Calgary', 'opponent_pt'=>4, 'is_decision'=>1, 'mins'=>59, 'secs'=>10, 'ga'=>1, 'sog'=>19],
];
$table = $this->table('games');
$table->insert($data)->save();
}
BeforeSave
// In a table or behavior class
public function beforeSave($event, $entity, $options)
{
// calculate record if part of decision
if (isset($entity->is_decision) && $entity->is_decision == 1){
//reset
$entity->l = 0;
$entity->w = 0;
$entity->t = 0;
$entity->otl = 0;
$entity->is_shutout = 0;
//calculate result of game
if($entity->is_overtime == 0){
//loss
if($entity->opponent_pt > $entity->user_pt)
$entity->l = 1;
elseif($entity->opponent_pt < $entity->user_pt)
$entity->w = 1;
//tie
elseif($entity->opponent_pt = $entity->user_pt)
$entity->t = 1;
}
else{
//ot loss
if($entity->opponent_pt > $entity->user_pt)
$entity->otl = 1;
}
//calculate shutout
if($entity->opponent_pt == 0)
$entity->is_shutout = 1;
$entity->abs_game_time = 0;
//calculate absolute game time
if(isset($entity->mins) && is_numeric($entity->mins) && $entity->mins > 0)
{
if(isset($entity->secs) && is_numeric($entity->secs) && $entity->secs > 0){
$entity->abs_game_time = ($entity->mins * 60 + $entity->secs)/60;
}
else
$entity->abs_game_time = $entity->mins;
}
}
}
Edit #1
Updated code snippets, still no go
Solution
This won't work because seeds don't use the Cake ORM.
use Phinx\Db\Table as BaseTable;
class Table extends BaseTable { /*...*/ }
Answered By - floriank
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.