【发布时间】:2016-11-10 03:46:25
【问题描述】:
我有一个 deliveryForecast 模型,我必须创建一个 eloquent 来从基于 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();
有什么想法吗?提前致谢。
【问题讨论】:
-
查看 Eloquent 文档的“多态”部分
-
在您的场景中,您需要在
DeliveryForecast模型中为每个单独的关系创建多个函数。
标签: php mysql laravel eloquent laravel-5.2