[英]Laravel Multiple linking column in another table with relationships?
我正在嘗試在Laravel中創建一個聯盟表,但是我又遇到了一些猜測,又是什么關系。 他們似乎從未在Laravel為我工作。 就像他們恨我一樣。
我有一個比賽的模態
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Match extends Model
{
protected $primaryKey = 'id';
protected $table = 'matches';
public $timestamps = false;
protected $guarded = ['id'];
}
和團隊模式,但具有matchs()函數
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match', 'team_one_id, team_two_id');
}
}
我認為問題在於team_one_id, team_two_id
因為teams主鍵可能位於另一張表的其中一個列中。 在matches()
count()
上調用count()
時,將引發錯誤。
SQLSTATE [42S22]:柱未找到:1054未知列'matches.team_one_id,team_two_id'在'where子句'(SQL:SELECT COUNT(*)作為從聚合
matches
,其中matches
。team_one_id, team_two_id
= 1和matches
。team_one_id, team_two_id
不為空)
你可以嘗試這種語法
返回$ this-> hasMany('modelPath','foreign_key','local_key');
這樣,您就可以實現它,在Team Model中添加這些關系和方法
public function homeMatches() {
return $this->hasMany('App\Database\Match', 'team_one_id');
}
public function awayMatches() {
return $this->hasMany('App\Database\Match', 'team_two_id');
}
public function matches() {
return $this->homeMatches->merge($this->awayMatches);
}
現在獲取數據
$team = Team::find(1);
$matches = $team->matches(); //now it will fetch all matches for both columns
如果要獲取匹配項作為屬性,則可以在團隊模型中添加一種方法
public function getMatchesAttribute()
{
return $this->homeMatches->merge($this->awayMatches);
}
現在您可以將匹配項提取為$matches = $team->matches;
這是區別
$team->matches
返回Illuminate\\Database\\Eloquent\\Collection
和
$team->matches()
返回Illuminate\\Database\\Eloquent\\Relations\\{Relation Name}
您不能像Team::with('matches')
這樣在Eager加載中使用matches
,因為matches
不是一種關系,並且會導致您的錯誤。 您可以做的是在急切加載中添加homeMatches
和awayMatches
,然后調用$team->matches()
。
$teams = Team::with('homeMatches', 'awayMatches')->get();
$teams->each(function ($team) {
print_r($team);
print_r($team->matches());
});
對照表中是否有一列鬃毛“ team_id”? 因為這是laravel文檔中用於映射表的默認命名約定。
如果您確實有該列並填充了數據,則可以從match()關系中刪除外鍵和本地鍵。 您不需要它。 Laravel將自動為您映射。
如果“比賽”表上沒有'team_id',請添加該列並添加相應的比賽ID。
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.