Eloquent 与多列的关系
Eloquent Relations With Multiple Columns
所以我有以下 match
table,其中包含参加那场比赛的球队的号码。我想与看起来像这样的 teams
建立关系:
团队Table
| id | number | name | etc |
| 1 | 1234 | Example | etc |
| 2 | 2345 | Example | etc |
etc...
匹配 Table
| id | match | red1 | red2 | blue1 | blue2 |
| 1 | 1 | 1234 | 1710 | 673 | 2643 |
| 2 | 2 | 2345 | 1677 | 4366 | 246 |
etc...
我想要 $this->match->where("match", "=", "2")->first()->teams();
。
我试过使用 hasMany() 但我似乎无法使用 red1, red2, blue1, blue3
列。
我尝试过的:
class Matches extends Model
{
protected $table = "match_table";
protected $fillable = [
"match_id",
"time",
"bluescore",
"redscore",
"red1",
"red2",
"red3",
"blue1",
"blue2",
"blue3",
];
public function teams()
{
return $this->hasMany("App\Models\Teams", "number", ["red1", "red2", "blue1", "blue2"]);
}
}
我最后做的只是遍历我想要的每一列,然后返回一个新的 Collection
和其中的结果。
public function teams()
{
$result = [];
foreach($this::$teamColumns as $column) {
$result[] = $this->hasMany("App\Models\Teams", "number", $column)->first();
}
return new Collection($result);
}
所以我有以下 match
table,其中包含参加那场比赛的球队的号码。我想与看起来像这样的 teams
建立关系:
团队Table
| id | number | name | etc |
| 1 | 1234 | Example | etc |
| 2 | 2345 | Example | etc |
etc...
匹配 Table
| id | match | red1 | red2 | blue1 | blue2 |
| 1 | 1 | 1234 | 1710 | 673 | 2643 |
| 2 | 2 | 2345 | 1677 | 4366 | 246 |
etc...
我想要 $this->match->where("match", "=", "2")->first()->teams();
。
我试过使用 hasMany() 但我似乎无法使用 red1, red2, blue1, blue3
列。
我尝试过的:
class Matches extends Model
{
protected $table = "match_table";
protected $fillable = [
"match_id",
"time",
"bluescore",
"redscore",
"red1",
"red2",
"red3",
"blue1",
"blue2",
"blue3",
];
public function teams()
{
return $this->hasMany("App\Models\Teams", "number", ["red1", "red2", "blue1", "blue2"]);
}
}
我最后做的只是遍历我想要的每一列,然后返回一个新的 Collection
和其中的结果。
public function teams()
{
$result = [];
foreach($this::$teamColumns as $column) {
$result[] = $this->hasMany("App\Models\Teams", "number", $column)->first();
}
return new Collection($result);
}