将数据存储到数据透视表 table laravel 8

store data into pivot table laravel 8

我在类别和产品之间有很多关系 类别模型

class Attribute extends Model implements Auditable
{
    use HasFactory, AuditableTrait;
    protected $fillable = ['category','sub_categ'];
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }

}

产品型号

class Product extends Model implements Auditable
{
    use HasFactory, AuditableTrait;
    protected $table = 'products';
    protected $fillable = ['name','price','description', 'details'];
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }
}

支点table

Schema::create('attributes_products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('product_id')->constrained('products')->onUpdata('cascade')->onDelete('cascade');
            $table->foreignId('attribute_id')->constrained('attributes')->onUpdata('cascade')->onDelete('cascade');
        });

在此之后我应该做什么我没有弄清楚附件如何在枢轴 table 和 return 中与产品一起工作作为 json 响应?

编辑

这是我正在处理的架构

我想给每个产品一个单独的类别 这是我的产品控制器存储功能

 public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'price' => 'required|numeric',
            'description' => 'required',
            'details' => 'required',
            'stocks' => 'required|numeric',
            //'discounts' => 'required|numeric'
        ]);

        $product = Product::create($request->only('name','price','description', 'details'));
        
        $product->stocks()->create([
            'quantity' => $request->stocks,
            'product_id' => $product->id
        ]);

        $product->discounts()->create([
            //'discount' => $request->discounts,
            'product_id' => $product->id
        ]);

        if($request->hasFile('images'))
        {
            foreach( $request->file('images') as $file)
            {
                $file->store('public/products');
                $product->images()->create([
                    'product_id' => $product->id,
                    'file_path'  => $file->hashName()
                ]);
            }
        }

        $product->categories()->sync([
            'product_id' => $product->id,
            'attribute_id'=> 1
        ]);
    }

在您的产品型号中检查您的关系。

public function categories()
{
    return $this->belongsToMany(Category::class);
}

通常枢轴 table 也只需要有 2 个 ID。所以在你的情况下只有 2 列:product_id & category_id.

您的 table 名称按照惯例应该是 category_product,否则,您应该在关系的第二个参数上指定它。

  • 也解决这个问题,你在 update 上打错了:

    $table->foreignId('attribute_id')->constrained('attributes')->onUpdate('cascade')->onDelete('cascade');

  • 最后附上:

    $product = Product::find(1);

    $product->categories()->attach($categoryId);

在文档中也有很好的解释:https://laravel.com/docs/8.x/eloquent-relationships