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 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退