繁体   English   中英

Laravel雄辩的关系多对多

[英]Laravel Eloquent Relationships Many To Many

我有一个程序,该程序定义了一个称为生产线的模型,该生产线将生产产品。 该生产线还具有许多投入来生产该产品,因此该生产线具有许多生产线。 我能够在模型本身没有问题的情况下建立这种关系。 一对多以这种方式指称自己

class ProductionLine extends Model {

  ...

  /**
   * The inputs for this production line
   */
  public function productionLines() {
    return $this->hasMany(ProductionLine::class);
  }

  /**
   * The consumer
   */
  public function productionLine() {
    return $this->belongsTo(ProductionLine::class);
  }
}

但是我在想如果生产线有很多消费者该怎么办。 我将如何建立这种关系? 我是否只需在ProductionLine模型中包含以下内容?

public function productionLines() {
 return $this->belongsToMany(ProductionLine::class);
}

在生产线模型中添加另一个类似的关系。

public function consumer()
{
    return $this->hasMany('App\Consumer');
}

请记住,Consumer表必须具有一个prod_id,该表指示该表属于哪个生产线

Eloquent允许您定义数据透视表和该表中的ID,这被证明是非常有用的。

我的模型称为ProductionLine,一条生产线有许多消费者和生产者,但消费者和生产者也是生产线。

那你该怎么做呢?

在模型中,我定义了自己的自定义ID和数据透视表'consumer_producer'。

public function producerProductionLines() {
  return $this->belongsToMany(ProductionLine::class, 'consumer_producer',
    'consumer_production_line_id', 'producer_production_line_id');
}

public function consumerProductionLines() {
  return $this->belongsToMany(ProductionLine::class, 'consumer_producer',
    'producer_production_line_id', 'consumer_production_line_id');
}

对于迁移,我创建了自己的

php artisan:make migration ConsumerProducer

创建迁移后,我添加了带有两个自定义ID的自定义数据透视表名称。

public function up() {
  Schema::create('consumer_producer', function(Blueprint $table) {
    $table->integer('consumer_production_line_id')->unsigned()->nullable();
    $table->integer('producer_production_line_id')->unsigned()->nullable();
    $table->timestamps();
  });
}

就是这样! 仅当您对ID的定义不同时,此方法才有效,否则两列将具有相同的名称,并且将无法正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM