【发布时间】:2018-09-26 03:20:58
【问题描述】:
我正在使用 Laravel 构建一个应用程序。它的结构如下:
一个用户 -> haOne -> 个人资料 -> hasMany -> 讨论 -> HasMany -> 回复 HasMany -> 赞
像往常一样,每个模型都有一个具有典型 CRUD 功能的控制器:DiscussionController、PaymentController、ImageController、ProfileController、RoleController、PostsControllers、MessageController。
在管理区域中,我管理和查看每个用户的所有相关信息。
web.php中的路由是:
Route::resource('admin-profiles', 'AdminProfileController');
我的问题出在 admin.profiles.show 视图中,该视图由该方法 AdminProfileController@show 提供:
public function show($slug)
{
$profile = Profile::where('slug', $slug)->first();
$page_name = $profile->name;
return view('admin.profiles.show', compact('profile', 'page_name'));
}
在这里,我需要有关用户的所有信息(个人资料、讨论、帖子的答案、图片、喜欢、付款、频道等)。
我可以在 AdminController 中构建一个 GIANT show 方法并将一大堆变量传递给该视图,如下所示:
$discussions = Discussion::where('profile_id', $profile->id)get);
$replies= Reply::where('profile_id', $profile->id)->paginate(4);
...
and so on until 27 queries
但在我看来这是一个糟糕的解决方案,因为我已经为每个模型配备了一个控制器。
我确实像这样调用了 UserController:
<span class="mt-3 small pull-right">
Accumulated Likes: {{ $user->profile->all_likes($user->id) }}
</span>
在 userController 中我做了:
public function all_likes($id) {
$user = User::find($id);
$profile = Profile::where('user_id', $user->id);
$discussions = Discussion::where('profile_id', $profile->id)->get();
$replies = array();
$all_likes = "";
foreach ($discussions as $discussion) {
foreach ($discussion->replies as $reply) {
$all_likes = $all_likes + count($reply->likes);
}
}
return $all_likes;
}
但它不起作用。
如何在 HTML 视图中调用不同控制器中的方法?
【问题讨论】:
-
{{ WhatController::public_staticFunction() }}
-
@Amarnasan,感谢您的回答,但是如何从 HTML 视图中调用“whateverController”?因为我收到错误:未定义的变量:all_likes(查看:...\views\admin\users\show.blade.php)。另一方面,这意味着我必须将所有控制器中的所有方法都设为静态?
-
{{ \App\Http\Controllers\WhateverController::public_staticFunction() }}。控制器只是另一个类。如果你想访问它的方法,你需要实例化它或者调用静态方法。
标签: laravel model-view-controller