2013-10-14 145 views
1

我从L3升级。一个客户有很多用户,而用户属于客户。Laravel 4 - 一对多关系返回null

迁移:

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; 

抛出一个异常(“试图获得非对象的属性“),因为客户为空。

,并试图:

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

抛出异常(调用未定义的方法照亮\数据库\查询\生成器::客户())。

我在做什么错?

回答

0

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

似乎以某种方式替换模型没有被调用。一旦我完全删除了原始用户模型,所有的工作都会奏效