Laravel,在关系中使用枢轴 table

Laravel, using pivot table in relations

Laravel 5.3,我有这两个型号:

用户,具有以下关系:

public function newFunctions()
{
    return $this->belongsToMany('App\NewFunctions', 'user_newfunctions');
}

新函数:

public static function getAllFunctions() {
    $functions = DB::table('new_functions as nf')
    ->select('nf.*')
    ->get();
    return $functions;
}

public function users(){
    return $this->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id');
}

(那个 getAllFunctions 在我收到这个代码之前就已经存在了......不要谈论它,还有很多其他控制器使用该方法......我不知道它是否是版本与否,但为什么老程序员不使用 all() 而不是 )

然后,在我的控制器中我这样做:

$user = User::findOrFail($id);

foreach ($user->newFunctions as $key => $function) {
    //dd($function);
    $user_new_functions[] = [$function->id, 69];
}
dd($user_new_functions);

有了 dd($function); 我明白了:

NewFunctions {#961 ▼
  #table: "new_functions"
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:7 [▶]
  #original: array:9 [▶]
  #relations: array:1 [▼
    "pivot" => Pivot {#962 ▼
      #parent: User {#770 ▶}
      #foreignKey: "user_id"
      #otherKey: "new_functions_id"
      #guarded: []
      #connection: null
      #table: "user_newfunctions"
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: false
      #attributes: array:2 [▼
        "user_id" => 814
        "new_functions_id" => 1
      ]
      #original: array:2 [▶]
      #relations: []

然后 dd($user_new_functions); 我得到:

array:2 [▼
  0 => array:2 [▼
    0 => 1
    1 => 69
  ]
  1 => array:2 [▼
    0 => 3
    1 => 69
  ]
]

我需要的是 69 我需要传递枢轴 table user_newfunctions

中的 function_count 的值

那个table是这个:

user_id | new_functions_id | function_count
-------------------------------------------
    814 |           1      |   5
    814 |           3      |   7

这样我就可以在 dd($user_new_functions); 中得到这个:

array:2 [▼
  0 => array:2 [▼
    0 => 1
    1 => 5
  ]
  1 => array:2 [▼
    0 => 3
    1 => 7
  ]
]

那个数组就是我的目标。请帮忙。

您需要在关系中包含 ->withPivot() 方法:

User.php:

public function newFunctions(){
  return $this->belongsToMany('App\NewFunctions', 'user_newfunctions')->withPivot(['function_count']);
}

NewFunctions.php:

public function users(){
  return $this->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')->withPivot(['function_count']);
}

现在,在查询关系时,->pivot 属性 将可用,其中包含 ->withPivot() 方法中的所有列。您可以将 69 替换为以下内容:

$user = User::with(['newFunctions'])->findOrFail($id);
foreach ($user->newFunctions as $key => $function) {
  $user_new_functions[] = [$function->id, $function->pivot->function_count];
}
dd($user_new_functions);

注意:为预先加载添加了 with(['newFunctions'])(可能提高性能,但不是必需的)

文档描述了如何检索略低于 "Many to Many" 关系信息的中间 table 列:https://laravel.com/docs/5.8/eloquent-relationships#many-to-many