Laravel belongsToMany table 插入查询中的顺序

Laravel belongsToMany table order in insert query

我有两个模型,Product 和 Filter。

一个产品可以有多个过滤器,一个过滤器可以有多个产品。多对多关系。

在我的产品中我有:

public function filters () {
    return $this->belongsToMany('App\Models\Filter');
}

在我的过滤器中:

public function products () {
    return $this->belongsToMany('App\Models\Product')->withTimestamps();
}

当我尝试插入产品并像这样保存过滤器后:

$filtersId = $request->filter;
$product->filters()->attach($filtersId);

我遇到了这个错误:

Base table or view not found: 1146 Table 'pontocom-moveis.filter_product' doesn't exist (SQL: insert into `filter_product` (`filter_id`, `product_id`) values (1, 31))

如何将订单更改为 product_filter?

您应该创建 table : filter_product 属性 :

filter_idproduct_id

该方法的第二个参数是 table 名称。

所以在这种情况下你应该使用:

public function filters () {
    return $this->belongsToMany('App\Models\Filter', 'product_filter');
}

public function products () {
    return $this->belongsToMany('App\Models\Product', 'product_filter')->withTimestamps();
}