2015-01-18 2 views
2

나는 세 테이블이있다.Laravel 1 대 다수의 관계를 삽입

  • 한 계약이 (수) 여러 개의 주문
  • 그러나 한 순서는 내가 다른 테이블을 생성 한 계약

수 있습니다 (order_contract) (여러 개의 주문 최종 가격이 될 수 있기 때문에 함께 합류) 주문 및 계약에 참여할 수 있습니다. 마이그레이션은 다음과 같습니다 :

내 테이블에 데이터를 삽입 할
public function up() 
{ 
    Schema::create('contracts', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->timestamps(); 
    }); 

    Schema::create('orders', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->integer('price'); 
     $table->timestamps(); 
    }); 

    Schema::create('order_contract', function(Blueprint $table) 
    { 
     $table->integer('order_id')->unsigned(); 
     $table->foreign('order_id')->references('id')->on('orders'); 
     $table->integer('contract_id')->unsigned(); 
     $table->foreign('contract_id')->references('id')->on('contracts'); 
     $table->timestamps(); 
    }); 
} 

/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('contracts'); 
    Schema::drop('orders'); 
    Schema::drop('order_contract'); 
} 

. 1. 새 계약을 삽입 (삽입에 내가 알고있는 $contract->id) 2. 두 개 이상의 주문 후 order_contract 테이블에 모든 단일 관계를 삽입

모델 한 순서에 부착 된 경우 :

**Order.php** 

class Order extends Eloquent{ 
protected $fillable = ['price']; 

public function contract(){ 
    return $this->belongsTo('Contract'); 
} 

}

**Contract.php** 

class Contract extends Eloquent{ 

public function orders(){ 
    return $this->hasMany('Order','order_contract','order_id','contract_id'); 
} 

}

내가이 상황 Laravels hasOne의에서 사용할 수있는 방법

() , hasMany(), belongsTo(), belongsToMany() 함수?

답변

1

OneToMany 관계를 사용할 때 중간 테이블을 만듭니다. ManyToMany 관계를 만들 때만 그렇게하면됩니다.

order_contact 테이블을 제거하고 주문 테이블에 "contract_id"열을 추가합니다 (선택 사항으로 nullable로 설정할 수 있으므로 계약서에 주문이 필요 없습니다).

$order1 = new Order; 
$order2 = new Order; 
$contract = new Contract; 
$contract->orders()->saveMany([$order1, $order2]); 

체크 아웃 :

그런 다음 당신은 당신이 뭔가를 할 수 있습니다 Contract 모델

class Contract extends Eloquent { 

    public function orders() 
    { 
     return $this->hasMany('Order'); 
    } 
} 

class Order extends Eloquent { 

    public function contract() 
    { 
     return $this->belongsTo('Contract'); 
    } 
} 

그런 다음 Order 모델에 기능을 추가 할 수 있습니다 docs on Attaching A Related Model

0 당신이 당신의 중간 테이블을 통해 그 일을 주장하는 경우

그렇게처럼 작업을 수행 할 수 있습니다

class Contract extends Eloquent { 

    public function orders() 
    { 
     return $this->hasManyThrough('Order', 'Contract', 'order_id', 'contract_id'); 
    } 
} 

참고 웅변 당신이 중간 모델을 가지고 있다고 가정.

Laravel에는 BelongsToManyThrough 함수가 없으므로 독자적인 메서드를 작성해야합니다. hasManyThrough는 바로 가기 일 뿐이므로이 방법으로 사용하기위한 것이 아닙니다 ...

나는 아직도 이런 식으로하는 것에 대해 충고합니다.

+0

나는 그것이 관계를위한 또 다른 테이블을 만드는 영리한 해결책이라고 생각했고, 또 다른 물건으로 주문 테이블을 채우지 않았고 가능한 모든 테이블을 기본으로 만들지 않았다. 당신의 해결책은 옳고 받아 들일 만하다. 하지만 "중간"테이블을 어떻게 사용할 수 있습니까? 고맙습니다. – jeugen

+0

나는 왜 그런 식으로 가고 싶은지 이해하지만 다른 길에 대해 생각해 보길 강력히 권합니다. 내 대답을 업데이트했습니다. – Jazerix

+0

결국 나는 중간 테이블없이 길을 선택했다. – jeugen

관련 문제