问题
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