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();
拋出異常(調用未定義的方法照亮\數據庫\查詢\生成器::客戶())。
我在做什麼錯?