简体   繁体   English

Laravel雄辩的ORM条件关系

[英]Laravel Eloquent ORM Conditional Relation

I can't seem to figure this out. 我似乎无法弄清楚。

I have 3 tables: User, Experience, Level (Simplified) 我有3个表格:用户,经验,级别(简体)

User: {id, string:name}
Experience: {id, user_id, int:amount}
Level: {id, string:level, int:experience}

//User class
public function experiences(){
    return $this->hasMany('Experience', 'user_id');
}

There are no database relations between Experience and Level. 体验和级别之间没有数据库关系。

How do I get the level, with something like this: 我如何获得水平,像这样:

public function level(){
    return $this->experiences()->has('Level.experience', '<', $this->experiences()->sum('amount'))->first();
}

I know how I could write it as a join, but I'd rather have Eloquent do it for me. 我知道如何将其编写为联接,但是我宁愿Eloquent为我做。

Example data: 示例数据:

User: {1, 'userOne'}
Experience: {1, 1, 10}
Level: {1, 'LevelOne', 5}

This user will then have Level "LevelOne" - Because the sum of Experience is 10, and above Level_id 1 with minimum experience 5. 然后,该用户将具有“ LevelOne”级别-因为经验总和为10,并且在Level_id 1以上且最低经验为5。

So what I have done, to solve this problem. 因此,我已经完成了解决此问题的工作。

My User model: 我的用户模型:

    public static function getLevel($experience){
    $level = Level::where('experience', '<=', $experience)->first();
    return $level;
    }

A view: 一个看法:

{{Auth::user()->getLevel(Auth::user()->experiences->sum('amount'))->level}}

That is the best 'hack' I could come up with :) 那是我能想到的最好的“ hack” :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM