【发布时间】:2019-07-29 02:15:11
【问题描述】:
我目前正在苦苦挣扎,因为我对 Laravel 中的关系还很陌生。 我有一个模型产品,它由一种模型材料制成。 材料可用于多种产品。
我有一个名为 product_material 的表来链接它们。
到目前为止我所拥有的 在产品中
public function material()
{
return $this->hasOne(Material::class, '');
}
在材料中
public function products(){
return $this->hasMany(Product::class, 'product_material');
}
但这给了我一个错误,说我的材料表中没有任何 product_id。
但是:我的材料不应该有 product_id,因为它在创建时没有链接到任何东西,它可以在多个产品中使用
编辑:数据库结构
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->string('code',45);
});
Schema::create('materials', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->string('code',45);
});
Schema::create('product_material', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->integer('product_id');
$table->integer('material_id');
});
【问题讨论】:
-
能分享一下数据库结构吗?