Laravel,在关系中使用数据透视表

时间:2019-07-10 14:27:06

标签: laravel relation

Laravel 5.3,我有两个模型:

用户,具有以下关系:

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

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,我需要传递数据透视表function_count中的user_newfunctions的值

那个桌子就是这个:

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

那个数组是我的目标。请任何帮助。

1 个答案:

答案 0 :(得分:1)

您需要在关系上包括->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'])以进行急切加载(可能会提高性能,但不是必需的)

文档介绍了如何检索中间表列,该列略低于“多对多”关系信息:https://laravel.com/docs/5.8/eloquent-relationships#many-to-many