代码之家  ›  专栏  ›  技术社区  ›  Richard

拉维雄辩的关系多对多

  •  0
  • Richard  · 技术社区  · 6 年前

    我有一个程序,它定义了一个叫做生产线的模型,这个生产线生产一个产品。这条生产线也有许多投入生产这种产品,所以这条生产线有许多生产线。我能把这种关系和模型本身联系起来。一对多这样称呼自己

    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 回复  |  直到 6 年前
        1
  •  0
  •   akshay kishore    6 年前

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

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

    记住consumer表必须有一个prod\u id来表示它属于哪个生产线

        2
  •  0
  •   Richard    6 年前

    雄辩允许您定义数据透视表和这个表中的id,这被证明是非常有用的。

    我的模型叫生产线,生产线有很多消费者和生产者,但消费者和生产者都是生产线。

    你怎么做到的?

    在模型中,我定义了自己的自定义id和pivot表“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时,这才起作用,否则这两个列将是相同的名称,而这是不起作用的。