Laravel 4 - 一对多关系返回null

时间:2013-10-14 07:24:59

标签: php laravel laravel-4 eloquent

我从L3升级。一个客户拥有许多用户,用户属于客户。

迁移:

Schema::create('customers', function($table)
{
 $table->increments('id');
 $table->string('name')->unique();
 $table->index('name');
 $table->string('full_name');
 $table->string('driver');
 $table->string('host');
 $table->string('database');
 $table->string('username');
 $table->string('password');
 $table->timestamps();
});

Schema::create('users', function($table)
{
 $table->increments('id');
 $table->string('email')->unique();
 $table->index('email');
 $table->integer('customer_id')->unsigned();
 $table->foreign('customer_id')->references('id')->on('customers')->on_update('cascade')->on_delete('cascade');
 $table->integer('domain_id')->unsigned();
 $table->foreign('domain_id')->references('id')->on('domains')->on_update('cascade')->on_delete('cascade');
 $table->string('password');
 $table->string('name');
 $table->string('state');
 $table->string('verification_token');
 $table->string('resend_verification_token');
 $table->string('change_password_token');
 $table->string('last_ip');
 $table->timestamp('last_login');
 $table->timestamp('verification_timestamp');
 $table->timestamp('change_password_timestamp');            
 $table->timestamps();
});

型号:

class Customer extends Eloquent {
  public function users()
  {
     return $this->hasMany('User');
  }
}

class User extends Eloquent {
  public function customer()
  {
     return $this->belongsTo('Customer');
  }
}

但尝试这种关系如下:

$user = User::find(1);
echo $user->customer->name;

抛出异常("尝试获取非对象的属性" ),因为customer为null。

尝试:

$user = User::find(1)->customer();

抛出异常(调用未定义的方法Illuminate \ Database \ Query \ Builder :: customer())。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我已将Laravel附带的User模型重命名为User_.php,并将其替换为我自己的模型。

似乎某种方式替换模型没有被调用。完全删除原始用户模型后,一切正常。