【问题标题】:Laravel belongsToMany table order in insert queryLaravel belongsToMany 在插入查询中的表顺序
【发布时间】:2016-08-06 05:39:30
【问题描述】:

我有两个模型,产品和过滤器。

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

在我的产品中,我有:

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))

如何将 order 更改为 product_filter?

【问题讨论】:

    标签: php mysql laravel many-to-many models


    【解决方案1】:

    方法的第二个参数是表名。

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

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

    【讨论】:

      【解决方案2】:

      您应该使用属性创建表:filter_product

      filter_idproduct_id

      【讨论】:

      • 我已经为这种关系创建了一个表。我忘记将关系名称传递给 belongsToMany。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多