首页 > 解决方案 > laravel 5.6 - 将正确的关系设置为渴望加载

问题描述

建立一个游戏网站。我有 3 张桌子。一个用户、等级(想想军事)和一个 rank_history 表。

Rank:
id, name, abbr, level, nextlevel, mintime


RankHistory:
id, user_id, rank_id, promoter, reason, created_at

public function User()
{
    return $this->belongsToMany(User::class);
}

public function PromotedBy()
{
    return $this->belongsToMany(User::class, 'rank_history', 'id', 'promoter');
}

public function Rank()
{
    return $this->belongstoMany(Rank::class);
}


user:
id, name, yadda (standard user stuff; nothing relevant)

public function RankHistory()
{
    return $this->hasMany(RankHistory::class);
}

我使用排名历史作为设置晋升、降级和历史的一种方式。最终,我希望能够输入$user->rank_detail($detail) 并让它返回等级的缩写、名称、级别等。

user.php

protected $with = ['rankhistory'];

public function rank_detail($detail)
{
    $rankId = $this->RankHistory->pluck('rank_id')->last();

    if (!$rankId) { $rankId = 1;}

    return Rank::where('id', $rankId)->value($detail);
}

这可行,但它会进行单独的查询调用以访问 Rank 表以获取详细信息。因为它非常安全,所以当我获得用户时,我会非常需要排名信息,所以我急切地加载这些信息就足够有意义了。问题是,怎么做?我已经尝试过hasmanythrough,,hasmany甚至尝试过添加$with =[ rankhistory.rank']任何东西。我也知道这可以通过在用户表中添加排名列来解决,但是如果用户可能经常更改排名,我希望尽可能保持用户表干净。加上拥有历史记录表可以为用户提供记录。

所以,问题是:我需要在用户(和/或其他文件)上放置什么来急切地加载用户的排名信息?

另外值得注意的是,rankhistory 表中的发起人是用户表上的 id 的 FK。我怎样才能得到这种关系呢?现在我可以返回 $history->promoter 并且它会给我一个 id.. 我怎样才能在没有不必要的查询调用的情况下获取用户信息?

标签: eloquentrelationshipeager-loadinglaravel-5.6

解决方案


试试这个:

class User
{
    protected $with = ['rankHistory.rank'];

    public function rankHistory()
    {
        return $this->hasOne(RankHistory::class)->latest();
    }

    public function rank_detail($detail)
    {
        if ($this->rankHistory) {
            return $this->rankHistory->rank->$detail;
        }            

        return Rank::find(1)->$detail;
    }
}

class RankHistory
{
    public function rank()
    {
        return $this->belongsTo(Rank::class);
    }
}

推荐阅读