2014-10-05 6 views
1

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은 별도의 테이블에와 AddressUser에 속하는 :

내 데이터베이스 구조는 (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'); 
    } 
} 

지금 나는 AddressUser을 만들고 내가 제약 조건 오류를 얻을 저장하려고 할 때. 두 가지 방법으로 시도했습니다 (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이 있어야합니다. 처음에는

답변

0

부모 model을 저장하고이 경우에는 User 그래서 그런 다음

$user = new User($data); 
$user->save(); 

을 시도 : 어쩌면

// $addressData ... 
$addressData['user_id'] = $user->id; 
$address = new Address($addressData); 
$address->save(); 

또는 : 나는 데이터베이스와

$user = new User($data); 
$user->address = new Address($addressData); 
$user->push(); 
+0

나는 '사용자'가 여기 '정의 엔터티'라고 말하고 싶습니다. 그리고'User'는'Address'를 가지고 있습니다. 내 생각에 당신이 말하는 것은 : "'Address'에서'user_id'를 제거하십시오. 하지만 "고아"주소를 만들 수 있습니다. – Matthijn

+0

'address' 테이블에'user_id'가 있습니까? –

4

시작할 것 디자인 우선.

users 테이블에 대해 내가 사용합니다 :

$table->increments('id'); 

$table->string('username')->unique(); 
$table->string('password', 64); 

address_id 여기에 필요하지 않습니다.

addresses 테이블에 대해 내가 사용합니다 :

$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'); 
$table->foreign('user_id') 
     ->references('id') 
     ->on('users') 
     ->onDelete('CASCADE'); 

당신은 주소 테이블에 외래 키를 사용 onDelete ('CASCADE`)를 추가해야합니다 - 당신이 사용자를 제거하면 현재 주소가 자동으로 제거됩니다. 고아가 된 주소는 없습니다.

이제 데이터를 삽입 : 당신은 어떤 user_id $addressData에 넣어 필요가 없습니다

$user = new User($data); 
$user->save(); 
$address = new Address($addressData); 
$user->address()->save($address); 

- 자동으로 채워집니다.

+0

그래, 그럴 가능성이있어. 그러나 나는 집 주소와 (물리적 인) 메일 주소를 구별하고 싶었다. 그래서 나는 'address_id'와'delivery_address_id'를 users 테이블에 가지고 있습니다. 사용자로부터 address_id를 제거하면 구분할 수 없습니다. – Matthijn

+0

@Matthijn User 테이블의'address_id'는'Address' 모델과 아무런 공통점이 없습니까? –