繁体   English   中英

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

[英]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我需要传递数据透视表user_newfunctionsfunction_count的值

那张桌子是这样的:

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']);
}

现在,在查询关系时,包含->withPivot()方法中的所有列的->pivot属性将可用。 您可以使用以下内容替换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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM