2016-11-10 87 views
1

获取数据我有一个deliveryForecast模型,我要创建一个雄辩得到基于2列从多个表中的数据。Laravel雄辩从多个相关表

这是我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

看一看在您的方案雄辩文档 – Scopey

+0

你需要创建'DeliveryForecast'模型为每个单独的关系内的多个功能的“多态”一节。 –

回答

2

正如@Scopey说,看看多态性关系:https://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations

为了实现多态的关系,你必须改变你的移植到以下几点:

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的方法如下:

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

而就是这样。但我强烈建议在你的QuotationDemo等车型添加关系:

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

当查询$forecast->document Laravel会自动获取正确的模型,没有任何其他的条件子句。

+0

感谢@Scopey和@GiedriusKiršys,这工作完全如我所料。最后一件事,是否有一种方法可以在多态性口才中添加另一种关系?这样的事情... '返回$这个 - > morphMany( '应用程序\ DeliveryForecast', '型') - >与( '顾客');' 因为都喜欢在deliveryForecast相关的表(”报价单”,‘演示’,‘服务部’)都有自己的CUSTOMER_ID列。 – frightnight