[英]Laravel Eloquent get data from multiple related table
i have a deliveryForecast model and i have to create an eloquent to get data from multiple table based on 2 columns. 我有一个deliveryForecast模型,我必须创建雄辩的才能从基于2列的多个表中获取数据。
this is my delivery_forecasts table 这是我的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();
});
the question is can i create the eloquent in model? 问题是我可以在模型中创造雄辩吗? or how to make condition?
或如何创造条件?
for example: 例如:
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 .....
}
}
i don't have idea to create the condition to eloquent and my query should be like this: 我没有创造雄辩条件的想法,我的查询应如下所示:
$delivery_forecast = DeliveryForecast::with('documents')
->get();
any idea guys? 有什么主意吗? thanks in advance.
提前致谢。
As @Scopey said, take a look at polymorphic relations: https://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations 正如@Scopey所说的,请看一下多态关系: https ://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations
In order to implement polymorphic relationship You have to change Your migration to following: 为了实现多态关系,您必须将迁移更改为以下内容:
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();
});
and then change DeliveryForecast
's method to following: 然后将
DeliveryForecast
的方法更改为以下方法:
public function document()
{
return $this->morphTo('type');
}
And that's all. 就这样。 But I would strongly suggest to add relationship in Your
Quotation
, Demo
and other models: 但我强烈建议在您的
Quotation
, Demo
和其他模型中添加关系:
public function deliveryForecasts()
{
return $this->morphMany('App\DeliveryForecast', 'type');
}
When querying $forecast->document
Laravel will automatically fetch correct model for without any other conditional clauses. 查询
$forecast->document
Laravel将自动获取正确的模型,而无需任何其他条件子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.