[英]Laravel Eloquent get data from multiple related table
我有一個deliveryForecast模型,我必須創建雄辯的才能從基於2列的多個表中獲取數據。
這是我的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();
有什么主意嗎? 提前致謝。
正如@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');
}
就這樣。 但我強烈建議在您的Quotation
, Demo
和其他模型中添加關系:
public function deliveryForecasts()
{
return $this->morphMany('App\DeliveryForecast', 'type');
}
查詢$forecast->document
Laravel將自動獲取正確的模型,而無需任何其他條件子句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.