Laravel:在模型类中获取当前对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16509027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:46:11  来源:igfitidea点击:

Laravel: Get current object inside model class

phplaravellaravel-3

提问by iamjonesy

I'm wondering if it's possible to access the current object when accessing a method of that object. for example the method fullname()below is used to get the full name of the user.

我想知道在访问该对象的方法时是否可以访问当前对象。例如fullname()下面的方法用于获取用户的全名。

class User extends Eloquent 
{

    public function itineraries() {
        return $this->has_many('Itinerary', 'user_id');
    }

    public function reviews() {
        return $this->has_many('Placereview', 'user_id');
    }

    public function count_guides($user_id){
        return Itinerary::where_user_id($user_id)->count();
    }

    public static function fullname() {
        return $this->first_name . ' ' . $this->last_name; // using $this as an example
    }
}

A user has a first_name field and a last_name field. Is there anyway I can do

用户有一个 first_name 字段和一个 last_name 字段。有没有我可以做的

$user = User::where('username', '=', $username)->first();

echo $user->fullname();

Without having to pass in the user object?

无需传入用户对象?

回答by Phill Sparks

You're almost there, you just need to remove the staticfrom your code. Static methods operate on a class, not an object; so $thisdoes not exist in static methods

你就快完成了,你只需static要从你的代码中删除。静态方法作用于一个类,而不是一个对象;所以$this在静态方法中不存在

public function fullname() {
    return $this->first_name . ' ' . $this->last_name;
}

回答by Collin Henderson

In your user model, your static function can look something like this

在您的用户模型中,您的静态函数可能如下所示

public static function fullname($username) {
    $user = self::where_username($username)->first();

    return $user->first_name.' '.$user->last_name;
}

You can then call this anywhere in your views/controllers etc with User::fullname($someonesUsername)

然后,您可以在视图/控制器等中的任何位置调用它 User::fullname($someonesUsername)