我有一个deliveryForecast模型,我必须创建一个雄辩的来根据2列从多个表中获取数据。
这是我的delivery_forecasts表
chrome.*
问题是我可以在模型中创造雄辩吗?或如何制定条件?
例如:
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 .....
}
}
任何想法的人?提前谢谢。
答案 0 :(得分:2)
正如@Scopey所说,看一下多态关系:https://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations
为了实现多态关系,您必须将迁移更改为以下内容:
function myFunction(element){
if (element){ //If the element is passed into this function
element.getElementsByClassName("myPopup")[0].toggle('show');
}
}
然后将 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');
}
Laravel会在没有任何其他条件子句的情况下自动获取正确的模型。