我正在尝试编写一个简单的社交媒体页面。显示视图应显示一个帖子,并在下面列出该帖子的所有评论。
我没有运气就尝试了几种不同的方法,这是我觉得我可能最接近成功的方法,有什么建议吗?
如果您认为问题出在其他地方,但我认为我的问题出在这4个文件中,那么我可以提供其他代码摘录。
web.php
Route::resource('post', 'PostController');
Route::resource('post', 'CommentController');
show.blade.php
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
@foreach ($comments as $comment)
<li>
User: {{$comments->user_name}} <br>
Comment: {{$comments->comment}} <br>
</li><br>
@endforeach
</ul>
PostController.php
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
CommentController.php
public function show($id)
{
$comments= Comment::find($id);
return view('post.show')->with('comments', $comments);
}
编辑1
Post.php
class Post extends Model
{
protected $fillable = ['title', 'description'];
function user() {
return $this->belongsTo('App\User');
}
function comment() {
return $this->hasMany('App\Comment');
}
}
答案 0 :(得分:1)
您可以通过建立模型之间的关系来获取这两个数据
我认为在您的两个模型中,关系将是这样,
发布模型
namespace App\Post;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
评论模型:
namespace App\Comment;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
因此,如果您想返回数据以查看,
PostController.php
public function show($id)
{
$post= Post::with('comments')->find($id);
$data = [
'post' => $post,
'comments' => $post->comments,
];
return view('post.show', $data);
}
CommentController.php
public function show($id)
{
$comments= Comment::with('post')->find($id);
$data = [
'post' => $comments->post,
'comments' => $comments,
];
return view('post.show' , $data);
}
答案 1 :(得分:1)
首先设置帖子和评论模型之间的关系
在邮寄模型中
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
评论模型
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
后控制器
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
写入刀片文件
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
@foreach ($post->comments as $comment) //get all the comments related to this post
<li>
User: {{$comment->user_name}} <br>
Comment: {{$comment->comment}} <br>
</li><br>
@endforeach
</ul>