2016-11-10 16 views
1

私はdeliveryForecastモデルを持っており、2カラムに基づいて複数のテーブルからデータを取得するには雄弁を作成する必要があります。Laravel Eloquent複数の関連テーブルからデータを取得

これは私がモデルに雄弁を作成することができている質問私delivery_forecastsテーブル

Schema::create('delivery_forecasts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->enum('type',array('Quotation','Demo','Service Unit','Freebie','Back Job','Site Visit')); 
     $table->string('type_id'); 
     $table->date('transaction_date'); 
     $table->time('transaction_time')->nullable(); 
     $table->enum('status',array('Pending','Approved','Cancelled'))->default('Pending'); 
     $table->boolean('queue')->default(0); 
     $table->timestamps(); 
    }); 

のですか?どのように状態を作るか?例えば

class DeliveryForecast extends Model 
{ 
    public function documents(){ 
     if(DeliveryForecast->type == 'Quotation'){ 
      return $this->belongsTo('App\Quotation','type_id','id'); 
     } 
     if(DeliveryForecast->type == 'Demo'){ 
      return $this->belongsTo('App\Demo','type_id','id'); 
     } 
     if(DeliveryForecast->type == 'Service Unit'){ 
      return $this->belongsTo('App\ServiceUnit','type_id','id'); 
     } 
     and so on ..... 
    } 
} 

私は雄弁に条件を作成するためのアイデアを持っていないと、私のクエリは次のようにする必要があります:

$delivery_forecast = DeliveryForecast::with('documents') 
     ->get(); 

任意のアイデアの男?前もって感謝します。

+1

あなたのシナリオでEloquentのドキュメント – Scopey

+0

の "polymorphic"セクションを見てみると、個々の関係ごとに 'DeliveryForecast'モデル内に複数の関数を作成する必要があります。 –

答えて

2

@Scopeyは、多型の関係を見て、言ったように:

Schema::create('delivery_forecasts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->morphs('type'); 
     $table->date('transaction_date'); 
     $table->time('transaction_time')->nullable(); 
     $table->enum('status', ['Pending', 'Approved', 'Cancelled'])->default('Pending'); 
     $table->boolean('queue')->default(0); 
     $table->timestamps(); 
    }); 

、その後DeliveryForecastの方法を変更します。https://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations

あなたが次への移行を変更する必要がある多型の関係を実装するために、 〜へ:

public function document() 
{ 
    return $this->morphTo('type'); 
} 

それだけです。しかし、私は強くあなたのQuotationDemoおよび他のモデルで関係を追加することをお勧め:

public function deliveryForecasts() 
{ 
    return $this->morphMany('App\DeliveryForecast', 'type'); 
} 

$forecast->document Laravelを照会し、自動的に他の条件節なしの正しいモデルを取得します。

+0

ありがとう@Scopeyと@GiedriusKiršys、これは私が期待どおり完全に動作します。最後に、多態性の雄弁に別の関係を追加する方法はありますか?このような何か... 'ますreturn $ this-> morphMany( 'アプリケーション\ DeliveryForecast'、 'タイプ') - >( '顧客')と;のようなdeliveryForecast内の関連するテーブルのすべてのために' (」見積もり '、'デモ '、'サービス単位 ')には独自のcustomer_id列があります。 – frightnight

関連する問題