【发布时间】:2019-09-28 04:17:15
【问题描述】:
我有一个collection of collection 到一个variable。我尝试将数据管理到此变量中,但它不起作用。
// User.php
public function projects()
{
return $this->belongsToMany(Project::class,'time_entries')
->withPivot('hours');
}
// Project.php
public function users()
{
return $this->belongsToMany(User::class, 'time_entries')
->withPivot('hours');
}
/// TimeEntries.php
public function user()
{
return $this->belongsTo( 'App\Model\User' );
}
public function project()
{
return $this->belongsTo( 'App\Model\Project','project_id' );
}
一个用户可以输入很多时间,他可以参与很多项目。项目可以有很多时间条目。
我试试这个:
$users = User::with('projects')->get();
foreach ($users$users = User::with('projects')->get();
foreach ($users as $user) {
foreach($user->projects() as $a) {
dump ($a);
}
}
我得到了
false
$user 的转储:
User {#715 ▼
#table: "users"
#connection: "redmine"
#with: array:1 [▶]
#fillable: array:19 [▶]
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:19 [▶]
#original: array:19 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:2 [▼
"projectrecap" => Collection {#714 ▼
#items: []
}
"projects" => Collection {#1414 ▼
#items: array:11 [▼
0 => Project {#17329 ▶}
1 => Project {#17338 ▶}
2 => Project {#17339 ▶}
3 => Project {#17340 ▶}
4 => Project {#17341 ▶}
5 => Project {#17342 ▶}
6 => Project {#17343 ▶}
7 => Project {#17344 ▶}
8 => Project {#17345 ▶}
9 => Project {#17346 ▶}
10 => Project {#17347 ▶}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
我希望所有用户都能看到他工作的所有项目以及他工作的总时长。
【问题讨论】:
标签: php laravel eloquent relationship