L3からのアップグレードです。1 つの顧客には多くのユーザーがいて、ユーザーは顧客に属します。
移行:
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() への呼び出し)。
私は何を間違っていますか?