我正在从 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;
抛出异常(“尝试获取非对象的属性”),因为客户为空。
并尝试:
$user = User::find(1)->customer();
抛出异常(调用未定义的方法 Illuminate\Database\Query\Builder::customer())。
我究竟做错了什么?