Laravel User relations stopped working

做~自己de王妃 提交于 2019-12-24 11:27:51

问题


I just downloaded and started a new project with the latest Laravel 4.2.

My problem is in the User model if I define any relation it's not working.

User Model

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');


    public function metadata()
    {
        return $this->hasOne('Metadata');
    }


    public function test()
    {
        return "hello test";
    }

}

Metadata Model

class Metadata extends Eloquent
{
    public $timestamps = false;

    protected $primaryKey = 'user_id';

    protected $table = "users_metadata";

    protected $fillable = array('user_id', 'first_name', 'last_name');

    public function user()
    {
        return $this->belongsTo('User');
    }
}

So if I do this

$user =  User::find(1);

dd($user->metadata);

I get back Null, and above i made a test method in my User model

If I do this:

$user =  User::find(1);

dd($user->test());

I get

Call to undefined method Illuminate\Database\Query\Builder::test() 

Why? It's clearly there. I put my code in an earlier version and it worked fine.

And what really confuses me is that if I do this:

$metadata =  Metadata::find(1);

dd($metadata->user);

It works fine with the belongsTo method, I tested User model with another relation - same results.

来源:https://stackoverflow.com/questions/24279959/laravel-user-relations-stopped-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!