【问题标题】:Laravel Eloquent get data from multiple related tableLaravel Eloquent 从多个相关表中获取数据
【发布时间】: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


【解决方案1】:

正如@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');
}

仅此而已。但我强烈建议在 Your Quotation、Demo 和其他模型中添加关系:

public function deliveryForecasts()
{
    return $this->morphMany('App\DeliveryForecast', 'type');
}

查询$forecast->document时,Laravel 会自动获取正确的模型,而无需任何其他条件子句。

【讨论】:

  • 感谢@Scopey 和@Giedrius Kiršys,这完全符合我的预期。最后一件事,有没有办法我可以在多态雄辩中添加另一个关系?像这样的东西...return $this->morphMany('App\DeliveryForecast', 'type')->with('customer'); 因为所有相关表在 deliveryForecast 中,例如 ('Quotation','Demo','Service Unit') 都有自己的 customer_id 列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2017-10-18
  • 2019-02-03
相关资源
最近更新 更多