use*_*002 3 php polymorphism laravel laravel-5
我想使用一个控制器来保存我对多个模型的评论。所以我使用以下存储方法创建了 CommentController:
public function store(Teacher $teacher, Request $request)
{
$input = $request->all();
$comment = new Comment();
$comment->user_id = Auth::user()->id;
$comment->body = $input['body'];
$teacher->comments()->save($comment);
return redirect()->back();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我有:
{!! Form::open([
'route' => ['teachers.comments.store', $teacher->id]
]) !!}
Run Code Online (Sandbox Code Playgroud)
这是有效的。如果我想使用同一个CommentController来存储学校的评论,我应该如何修改控制器的store方法?
Adam 的解决方案很棒,但我不会以这种方式对模型的名称空间进行硬编码。相反,我要做的是利用 Laravel 的Relation::morphMap(),你可以在这里查看: https: //laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations
这样,您还可以使数据库条目更具可读性。我建议使用服务提供商来映射变形。
另外,Model基类有一个getMorphClass()方法,所以
$comment->commentable_type = 'App\\Models\\'.$model;
我会使用
$comment->commentable_type = $model->getMorphClass();
这样你就可以将 Laravel 的逻辑集成到你的代码中。
| 归档时间: |
|
| 查看次数: |
6520 次 |
| 最近记录: |