代码之家  ›  专栏  ›  技术社区  ›  AH Rasel

Laravel 5.7一对多列关系

  •  0
  • AH Rasel  · 技术社区  · 6 年前

    我有球队和比赛桌。所有比赛信息保存在比赛桌上,包括两个队、冠军队、比赛时间等。

    在比赛桌上,我有三个外勤队,一队,二队,优胜者队 我想把这些领域与团队表联系起来

    这是我的密码

    团队模式

    class Team extends Model
    {
        public function league()
        {
            return $this->belongsTo('App\League');
        }
    
    
    
          public function matchs()
            {
                return $this->hasMany('App\Match');
            }
    
        }
    

    匹配模型

    class Match extends Model
    {
        public function team_1()
        {
            return $this->belongsTo('App\Team','id');
        }
    
        public function team_2()
        {
            return $this->belongsTo('App\Team','team_2');
        }
    
        public function winner()
        {
            return $this->belongsTo('App\Team','winner');
        }
    
        public function league()
        {
            return $this->belongsTo('App\League');
        }
    
        public function teams() {
            return $this->team_1()->merge($this->team_2());
        }
    }
    

    迁移文件

    Schema::create('matches', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('team_1')->unsigned()->index();
                $table->integer('team_2')->unsigned()->index();
                $table->integer('league_id')->unsigned()->index();
                $table->integer('winner')->nullable();
                $table->dateTime('match_time');
                $table->timestamps();
    
                $table->foreign('team_1')->references('id')->on('teams')
                    ->onDelete('restrict')
                    ->onUpdate('cascade');
    
                $table->foreign('team_2')->references('id')->on('teams')
                    ->onDelete('restrict')
                    ->onUpdate('cascade');
    
                $table->foreign('league_id')->references('id')->on('leagues')
                    ->onDelete('restrict')
                    ->onUpdate('cascade');
    
                $table->foreign('winner')->references('id')->on('teams')
                    ->onDelete('restrict')
                    ->onUpdate('cascade');
            });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Raúl Monge    6 年前
    public function team_1()
    {
        return $this->belongsTo('App\Team', 'team_1');
    }
    
    public function team_2()
    {
        return $this->belongsTo('App\Team', 'team_2');
    }