Laravel에서 작동하는 외래 키 제약 조건을 얻으려고합니다. 그러나 나는 더 이상 내 모델을 구할 수 없다.Laravel 외래 키 제약 조건과 모델 관계
Schema::create($this->tableName, function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('password', 64);
$table->integer('address_id')->unsigned();
});
Schema::create($this->tableName, function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->string('surname');
$table->string('street');
$table->string('number');
$table->string('town');
$table->string('country');
});
는 그래서 Address
은 별도의 테이블에와 Address
가 User
에 속하는 :
내 데이터베이스 구조는 (I 불필요한 코드를 제거했습니다) 다음과 같이 설정입니다. User
에는 Address
이 있습니다. 내가 해당 모델을 만든
다음 :
Class User extends Model
{
public function address()
{
return $this->hasOne('Address');
}
}
Class Address extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
지금 나는 Address
와 User
을 만들고 내가 제약 조건 오류를 얻을 저장하려고 할 때. 두 가지 방법으로 시도했습니다 (User
먼저 저장하고 Address
먼저 저장). 둘 다 오류가 발생합니다.
내가 가진 첫 번째 생각이 있었다 :
// Create a new user
$user = new User($data);
$address = new Address($addressData);
$address->user()->associate($user);
$user->push(); // Error here
하지만이 오류 제공 : 다음
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`eet`.`users`, CONSTRAINT `users_address_id_foreign` FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`)) (SQL: insert into `users` (`username`, `email`, `password`, `type`, `phone`, `cellphone`, `newsletter_week`, `ip`, `updated_at`, `created_at`) values (adsadsad, [email protected], passWO23dw00, customer, 123123213, 1234567890, 1, ::1, 2014-10-05 19:56:03, 2014-10-05 19:56:03))
그래서 나는
Address
먼저 절약 노력하고
User
같은 :
$user = new User($data);
$address = new Address($addressData);
$address->save(); // Error here
$address->user()->associate($user);
$user->push();
을
그러나 다음 오류가 생성됩니다.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `addresses` (`name`, `surname`, `street`, `number`, `town`, `country`, `user_id`) values (Foo, Bar, FooStreet, 200, Townsville, nl,))
그럼 어떻게하면 좋은가요? 나는 User
에 대해 address_id
필드를 null로 만들 수 있지만 그 방법이 좋습니까? User
에는 항상 Address
이 있어야합니다. 처음에는
나는 '사용자'가 여기 '정의 엔터티'라고 말하고 싶습니다. 그리고'User'는'Address'를 가지고 있습니다. 내 생각에 당신이 말하는 것은 : "'Address'에서'user_id'를 제거하십시오. 하지만 "고아"주소를 만들 수 있습니다. – Matthijn
'address' 테이블에'user_id'가 있습니까? –