【问题标题】:Managing an incrementing field in a model with ATK4 (not a mysql autoincrement column)使用 ATK4 管理模型中的递增字段(不是 mysql 自动递增列)
【发布时间】:2011-10-16 08:33:48
【问题描述】:

好的 - 这可能很简单,但我无法想象我需要在 ATK4 中放置什么。

我有一个包含 id、name 和 reference 列的表(团队)。 id 是一个自动增量列和一个引用。表格中有3行这样的

 id,  name,     last_ref
 1,  'Team 1',  1000
 2,  'Team 2',  1000
 3,  'Team 3',  2000

还有另一个表(故事),其中包含 id、name、team_id 和 team_ref 列,在填充数据后看起来像这样

 id, name, team_id, team_ref
  1, 'Story A', 1, 1001
  2, 'Story B', 1, 1002 
  3, 'Story C', 1, 1003
  4, 'Story D', 2, 1001
  5, 'Story E', 3, 2001

对于故事表中的每次插入,都会在团队表中查找 team_ref,将其递增 1,并将结果存储在故事行中。 last_ref 字段也应立即更新,以防其他人也向故事表中插入新行。

因此,在将上述内容插入故事表后,团队表应如下所示,因此每个团队都保持自己的顺序并按顺序分配数字。

 id,  name,     last_ref
 1,  'Team 1',  1003
 2,  'Team 2',  1001
 3,  'Team 3',  2001

插入故事记录的页面是 CRUD,但不确定我是否应该将逻辑插入 CRUD、页面或模型本身。它应该只影响插入,我认为它可能应该是 addField('last_ref') 上的 defaultValue 但我可以将它设为一个函数吗?该函数应该在哪里定义?

虽然不是必需的,但很高兴增加 last_ref 应该跳过当前团队的表中已经使用的任何引用(如果通过 CRUD 以外的其他方式插入)。

提前致谢。

【问题讨论】:

    标签: php model counter atk4


    【解决方案1】:

    当然,Model 是这样与数据库相关的逻辑的正确位置。

    重新定义 beforeInsert 函数,该函数将锁定表格,查找最大元素并设置引用:

    function beforeInsert(&$data){
        $this->myLockTable();
        $next_ref = $this->myGetNextRef();
        $data['team_ref']=$next_ref;
        return parent::beforeInsert($data);
    }
    function afterInsert($id){
        parent::afterInsert($id);
        $team = $this->add('Model_Team')->loadData($this->get('team_id'));
        $team->set('last_ref',$this->get('team_ref'))->update();
        $this->myUnlockTable();
    }
    

    此处以“my”开头的函数将是您自定义实现的函数。

    然后,假设您正确使用模型,将没有“其他方式”插入记录,您无需担心跳过这些条目。

    【讨论】:

    • 非常感谢。关于跳过值的问题是需要将数据导出到 excel 以供离线工作,但如果模型正确,那么当数据从 excel 重新加载到系统中时,我可以分配团队参考。
    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多