我有一个程序,它定义了一个叫做生产线的模型,这个生产线生产一个产品。这条生产线也有许多输入来生产这个产品,所以这条生产线有很多生产线。我能够将这种关系与模型本身的问题联系起来。以这种方式引用自身的一对多
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);
}发布于 2018-08-25 15:39:56
在您的生产线模型中添加另一个类似这样的关系。
public function consumer()
{
return $this->hasMany('App\Consumer');
}只需记住,消费者表必须有一个prod_id来表示它属于哪条生产线
发布于 2018-08-26 01:28:30
Eloquent允许您定义数据透视表和此表中的in,这被证明非常有用。
我的模型叫做ProductionLine,一条生产线有许多消费者和生产者,但消费者和生产者也是生产线。
那么如何做到这一点呢?
在模型中,我定义了自己的自定义I和数据透视表“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在创建迁移时,我添加了带有两个自定义ids的自定义数据透视表名称。
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();
});
}就是这样!只有当您以不同的方式定义if时,这才有效,否则两个列将具有相同的名称,这将无法工作。
https://stackoverflow.com/questions/52014091
复制相似问题