【问题标题】:I can not add methods to User Model in Laravel 5.4 ..!我无法在 Laravel 5.4 中向用户模型添加方法 ..!
【发布时间】:2018-04-04 09:32:04
【问题描述】:

我正在使用 Laravel 5.4。我有我在用户模型中创建的方法。当我想从 User 模型创建一个对象并调用我自己的方法时,我无法访问我添加的方法。

User Model 是从 5.4 的 Authenticable 类派生的,该类更早是从 Model 类派生的。我认为问题在于它。我真正想做的是设置belong_to、has_many 结构以将用户模型与其他模型相关联。

但是对于用户模型,我不这样做。你有什么推荐的?

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getMakale()
    {
        return $this->hasMany(Makale::class, 'user_id', 'id');
    }    

}

    $author = User::first();
    return  method_exists($author,'getMakale');

//最终变为假

【问题讨论】:

  • 这不是我想要的
  • 简而言之,您想创建与其他模型的关系,但您不想将这些模型称为关系,但您试图简单地调用创建连接的方法?为什么这是必要的?

标签: php laravel methods model


【解决方案1】:

我相信你可能是setting an accessor,而不是关系。在这种情况下,我认为您想将该函数命名为:

public function haberler()
{
    return $this->hasMany(Makale::class, 'user_id', 'id');
}

public function makales()。在你的函数名称前加上 getset 会在 Laravel 中产生意想不到的后果。

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 2020-05-26
    • 2022-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 2020-01-27
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多