2

我想知道在访问该对象的方法时是否可以访问当前对象。例如,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
    }
}

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

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

echo $user->fullname();

无需传入用户对象?

4

2 回答 2

7

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

public function fullname() {
    return $this->first_name . ' ' . $this->last_name;
}
于 2013-05-12T17:31:20.470 回答
3

在您的用户模型中,您的静态函数可能看起来像这样

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

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

然后你可以在你的视图/控制器等的任何地方调用它User::fullname($someonesUsername)

于 2013-05-12T16:04:26.157 回答