[英]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.