【问题标题】:Laravel 5.3: Creating a PostCommentsController for a BlogLaravel 5.3:为博客创建 PostCommentsController
【发布时间】:2017-03-05 04:10:45
【问题描述】:

我正在创建一个包含帖子、类别、评论和评论回复的博客。

目前我在

中有以下内容

PostCommentsController.php

public function show($id)
{
     $post = Post::findOrFail($id);     
     $comments = $post->blog_comments;
     return view('admin.comments.show', compact('comments'));
}

我的问题是,我已经更改了 post 表中的 postID 列,这与使用 $id 时 Laravel post_id 中的预期不同,对吧?

在这种情况下,我该如何进行才能完成这项工作?

【问题讨论】:

  • 你的意思是你的主索引从id变成了postID?

标签: php database laravel controller


【解决方案1】:

试试这个,我假设你有模型 post.php,BlogComment.php。 在模型文件 post.php 中

public function blog_comments()
{
  return $this->hasMany(BLogComments::class,'postID')
}

希望这会有所帮助

【讨论】:

  • 当然,我在 Post 模型中有这个:` public function cmets(){ return $this->hasMany('App\Comment'); } 将通过以下方式重新调整所有功能,并尽快让您知道结果: public function cmets(){ return $this->hasMany('App\Comment', 'postID'); }`
  • 只需将第二个参数作为 PostID 传递,否则它将采用 laravel 默认值,如您所说的 tableName_id (post_id)
  • 很高兴为您提供帮助 :)。如果这解决了您的问题,请将此标记为已接受并投赞成票,因为接受的答案将帮助其他访问该网站的人解决他们的问题,如果他们遇到同样的问题。谢谢:)
  • 我已经做到了,但我的声誉仍然不够高,无法计算:)
【解决方案2】:

如果我理解正确,你可以在任何模型的类中选择主键,只需要改变变量

protected $primaryKey = 'id'; // For you case it will be 'post_id'

【讨论】:

  • class Post extends Model { // protected $table = 'blog_posts'; protected $primaryKey = 'blogPostID';
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
相关资源
最近更新 更多