php - Laravel:获取模型类中的当前对象

标签 php laravel laravel-3

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

无需传入用户对象?

最佳答案

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

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

关于php - Laravel:获取模型类中的当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16509027/

相关文章:

laravel - 为什么在 Laravel 中不工作组中间件?

mysql - 需要将原始查询转换为 laravel Eloquent

php - Laravel - 对所有路由使用 ( :any? ) 通配符?

php - 从 mysql 创建 JSON 结果

php - 几个页面布局问题

php - 如何在 Laravel 5.1 中自动加载自定义类?

php - 在 Laravel 中使用自动 Controller 路由是个坏主意

php - 使用URL条目从mysql数据库在索引php页面上加载数据

php - 下拉选项在选择时会发生变化

mysql - orderBy 不使用 as 关键字 laravel