yii2 如何使多个列一起唯一

how to make multiple columns unique together yii2

我尝试创建足球 table 应用程序。我有 3 个 tables - teams(id, name)matches(id, home_team_id, away_team_id, round_id)rounds(id, round_num)home_team_idaway_team_id是外键,参考teamstable。 round_id 是 f.k。参考 rounds table。例如,我有 4 个团队 - juventusmilanchelseaarsenal。所以如果我想创建匹配 - 首先我创建回合。我在这里只需要插入轮数(例如第 4 轮)。然后我在这一轮中添加比赛 - 选择主队(例如 juventus),然后选择客队(例如 milan),然后提交。问题是,下次我创建比赛时,我不应该能够创建已经玩过的比赛。如果 juventus 主场对阵 milan,用户将无法再次创建此比赛。所以我需要 home_team_idaway_team_id 在一起是独一无二的,并且只能在一起(而不是分开)!我该怎么做?我试着验证它

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

但它并没有阻止存储数据和显示错误消息,而是覆盖了现有的匹配项

只需将其放入您的 "Match" 模型规则中即可:

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

您必须确保:

  1. 您的属性验证已启用$model->save(true)
  2. 场景数组中存在该属性,如果您使用它。

    public function scenarios(){
        return array_merge(parent::scenarios(), [
            ...,
            self::SPECIFIC_SCENARIO => ['home_team_id']
        ]);
    }