Laravel,在关系中使用透视表
Laravel 5.3,我有两种型号: 用户,使用此关系:Laravel,在关系中使用透视表,laravel,relation,Laravel,Relation,Laravel 5.3,我有两种型号: 用户,使用此关系: public function newFunctions() { return $this->belongsToMany('App\NewFunctions', 'user_newfunctions'); } 新功能: public static function getAllFunctions() { $functions = DB::table('new_functions as nf') ->
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\u new\u函数)代码>我得到:
array:2 [▼
0 => array:2 [▼
0 => 1
1 => 69
]
1 => array:2 [▼
0 => 3
1 => 69
]
]
我需要的是,相反,69
我需要传递透视表user\u newfunctions
那张桌子是这张:
user_id | new_functions_id | function_count
-------------------------------------------
814 | 1 | 5
814 | 3 | 7
因此,我将在dd($user\u new\u函数)中使用代码>此:
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']);
}
public function users(){
return $this->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')->withPivot(['function_count']);
}
NewFunctions.php
:
public function newFunctions(){
return $this->belongsToMany('App\NewFunctions', 'user_newfunctions')->withPivot(['function_count']);
}
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);
注意:添加了(['newFunctions'])
,用于快速加载(可能会提高性能,但不是必需的)
文档描述了如何检索略低于“多对多”关系信息的中间表列:我猜第二次你是我的英雄,因为你的名字看起来是紫色的。伟大的谢谢我现在就去测试,看起来一切正常。