dongmao7195 2016-12-06 19:39
浏览 34
已采纳

如何使多个列一起独特yii2

i try to create football table app. i have 3 tables - teams(id, name), matches(id, home_team_id, away_team_id, round_id) and rounds(id, round_num). home_team_id and away_team_id are foreign keys, reference to teams table. and round_id is f.k. references to rounds table. for example i have 4 teams - juventus, milan, chelsea, arsenal. so if i want to create match - first i create round. all i need here is just insert number of round(for example 4th round). then i go and add matches in this round - choose home team(for example juventus) and then choose away team(for example milan) and then submit. the problem is, next time when i will create match, i shouldn't be able to create match that already been played. if juventus played home against milan user shouldn't be able to create this match again. so i need home_team_id and away_team_id to be unique together, and only together(not separately)! how should i do this? i tried to validate it like

[['home_team_id', 'away_team_id'],
         'unique', 'targetClass' => Match::className(),
       'targetAttribute' => ['home_team_id', 'away_team_id']],

but instead of prevent storing data and show error message,it override existing match

  • 写回答

1条回答 默认 最新

  • dpp34603 2016-12-07 14:37
    关注

    Just put it in your "Match" model's rules:

    ['home_team_id','unique', 'targetAttribute' => ['home_team_id', 'away_team_id']]
    

    You must to make sure that:

    1. Your attributes validation enabled $model->save(true)
    2. Attribute exist in scenario array if you use it.

      public function scenarios(){
          return array_merge(parent::scenarios(), [
              ...,
              self::SPECIFIC_SCENARIO => ['home_team_id']
          ]);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题