Laravel-获取来自多态关系的所有数据的集合

时间:2018-10-13 00:17:58

标签: laravel polymorphism

我想从单个项目集中的多态关系中获取所有数据(行结果)

这是场景:

matches table
--id

match_details_pivot table
--id
--match_id_fk   # a foreign key on match.id table
--details_id    # polymorphic relation model id
--details_type  # polymorphic relation model

match_details_football table
--id
--match_details_id_fk

关系如下:

Match -> hasOne MatchDetailsPivot -> hasMany MatchDetailsFootball

Laravel模型:

class Match extends Model
{
    protected $table = 'matches';

    public function details()
    {
        return $this->hasOne(MatchDetails::class, 'match_id_fk');
    }
}

class MatchDetailsPivot extends Model
{
    const MORPH_ID      =   'details_id';
    const MORPH_COLUMN  =   'details_type';

    protected $table = 'match_details_pivot';

    public function match()
    {
        return $this->belongsTo(Match::class, 'id', 'match_id_fk');
    }

    public function matchData()
    {
        return $this->morphTo('matchData', self::MORPH_COLUMN, self::MORPH_ID);
    }
}

class MatchDetailsFootball extends Model
{
    protected $table = 'match_details_football';

    public function matchDetails()
    {
        return $this->morphMany(MatchDetailsPivot::class, 'matchData');
    }
}

示例场景:

  • 比赛表具有 1 条记录,其ID为 50
  • Match_details_pivot 表包含ID为12的 1 记录,其中外国ID 指向ID为 50 的匹配表strong>。
  • Match_details_pivot 表还具有多态关系,以加载ID = 15
  • 的MatchDetailsFootball模型
  • Match_Details_Football 表具有 2 条ID为 15 16 的记录,并且它们都具有外键指向数据透视表的引用,该ID为 12

上述情况下的表记录示例:

matches
id    
50

match_details_pivot
id    match_id_fk    details_id    details_type
12    50             15            MatchDetailsFootball


match_details_football
id    match_details_id_fk    score    team
15    12                     5        Manchester
16    12                     5        Arsenal

问题:数据透视表中的多态关系,默认为要加载的多态表的ID列(match_details_football.id),但是,我需要它指向不同的外部id列(match_details_football.match_details_id_fk)。

获取记录:

$test = Match::with('details')->with('details.matchData')->where('matches.id', 50)->get();

这将返回具有单个MatchDetailsPivot关系和单个MatchDetailsFootball关系的单个Match集合。

我需要它来返回所有MatchDetailsFootball关系。

如何在Laravel中实现?

0 个答案:

没有答案