v7中的belongsToMany返回一个空数组

时间:2020-08-20 21:06:40

标签: laravel

我的客户有一个基于4.x的旧站点,我正尝试使用7.4。我大部分工作都在进行中,但是陷入了belongsToMany关系中

我有一个Manufacturer类,该类通过名为Subcategories的表与membercategory有多对多的关系。但是,subcategories属性始终返回一个空数组。我想念什么?

membercategory
+------+------------------+-----------------+
| ID   | FKManufacturerID | FKSubCategoryID |
+------+------------------+-----------------+
| 3203 |               24 |             301 |
| 3202 |               24 |             292 |
| 3201 |               24 |             295 |
+------+------------------+-----------------+

和我的Manufacturer

class Manufacturer extends Model {

  public function subcategories() {

    # have tried swapping the two FK parameters, same result
    return $this->belongsToMany('App\Subcategory','membercategory','FKSubCategoryID','FKManufacturerID');
  }
}

我正在使用此功能在我的控制器中进行测试

dd($manufacturers[0]->subcategories);

其中$manufacturers[0]返回Manufacturer ID=24的对象

2 个答案:

答案 0 :(得分:1)

根据documentation,您的代码应如下所示:

class Manufacturer extends Model {

  public function subcategories() {

    return $this->belongsToMany('App\Subcategory','membercategory','FKManufacturerID','FKSubCategoryID');
  }
}

查看belongsToMany签名:

public function belongsToMany(
    $related, 
    $table = null, 
    $foreignPivotKey = null, 
    $relatedPivotKey = null,
    $parentKey = null, 
    $relatedKey = null, 
    $relation = null) {}

您将看到需要在第4个参数中包含相关列,而在第3个参数中包含外来列。

编辑

确保模型表和数据透视表中的列类型匹配。

此外,根据belongsToMany签名,如果不是默认值,则应添加parentKeyrelatedKey参数:idID! = id

Here is a list of eloquent model conventions in Laravel 7.x,您会看到:

Eloquent还将假定每个表都有一个名为id的主键列。您可以定义一个受保护的$ primaryKey属性以覆盖此约定:

这意味着如果两个模型表都具有名为“ ID”的主键列(如您在聊天中所显示的那样),则代码应如下所示:

class Manufacturer extends Model {

  public function subcategories() {

    return $this->belongsToMany(
      'App\Subcategory',
      'membercategory',
      'FKManufacturerID',
      'FKSubCategoryID'
      'ID',
      'ID'
    );
  }
}

答案 1 :(得分:0)

只需替换第三列和第四列的位置,就像这样:

return $this->belongsToMany('App\Subcategory', 'membercategory', 'FKManufacturerID', 'FKSubCategoryID');