首页 文章

laravel 5.6 - 设置与急切负载的正确关系

提问于
浏览
0

Build 游戏网站 . 我有3张 table . 用户,等级(想想军事等)和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表来获取详细信息 . 因为它非常安全,所以当我得到用户时,我将需要很多等级信息,这对我来说足够有意义地加载这些 . 问题是,怎么样?我试过 hasmanythroughhasmany ,甚至尝试添加 $with =[ rankhistory.rank'] 没什么用 . 我也知道这可以通过在用户表中添加一个排名列来解决,但是如果用户可能经常更改排名,我希望尽可能保持用户表的清洁 . 加上历史记录表可以为用户提供记录 .

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

另外值得注意的是,rankhistory表中的启动器是用户表上的FK到id . 我怎么会得到这种关系?现在我可以返回$ history-> promoter,它会给我一个id ..如何在没有不必要的查询调用的情况下获取用户信息?

1 回答

  • 1

    试试这个:

    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);
        }
    }
    

相关问题