变异模型数据

时间:2017-02-10 12:32:16

标签: laravel laravel-5 model

我想操纵模型中的数据我该怎么做?我正在尝试这个,但它不起作用:

class Character extends Model
{
    //Get players by level
    public function scopeGetPlayersByLevel($query){
       $output = $query->orderBy('level', 'desc')->get();
       $output->classid = 100;
       return $output;
    }

    //Get online status
    public function account(){
        $account = $this->belongsTo(Account::class, 'account_name', 'username');
        $account->online = $account->online == 1 ? 'Online' : 'Offline';
        return $account;
    }
}

2 个答案:

答案 0 :(得分:3)

Account模型中的

Define an accessor

public function getOnlineAttribute($value)
{
    return $value === 1 ? 'Online' : 'Offline';
}

答案 1 :(得分:1)

试试这个:

a)定义帐户模型的关系

b)创建一个访问者(我称之为getAccountStrAttribute,这意味着你这样称呼它:$acc->account_str)。

c)胜利

class Character extends Model
{
    // Relationship defined
    public function account() {
      return $query->belongsTo(Account::class, 'account_name', 'username');
    }

    //Get online status
    public function getAccountStrAttribute(){
        return $this->account->online ? 'Online' : 'Offline';
    }

    // I can't figure out what you want this function to return/do :/
    //Get players by level
    public function scopeGetPlayersByLevel($query){
       $output = $query->orderBy('level', 'desc')->get();
       $output->classid = 100;
       return $output;
    }
}