Laravel雄辩的关系多对多

时间:2018-08-25 04:38:57

标签: php laravel eloquent

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

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);
}

2 个答案:

答案 0 :(得分:0)

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

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

请记住,Consumer表必须具有一个prod_id,以表明它属于哪个生产线

答案 1 :(得分:0)

口才可以让您定义数据透视表和该表中的ID,这被证明是非常有用的。

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

那你怎么做?

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

static constexpr bool value { type::value };

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

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

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

php artisan:make migration ConsumerProducer

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