php - Laravel5.8:从表中检索数据
问题描述
我正在构建活动信息页面。
我的帖子表有 post_id 和 category_id。
现在我可以从帖子表中检索帖子信息(图像、组织者、标题、地点、地图、日期、描述)。
但我无法检索类别名称。另外,我的帖子有标签。我需要检索标签的名称。
我不知道如何获取这些数据并显示在我的帖子/show.blade.php 上。
如果有人帮助我,我很高兴。PostsController.php
public function store(CreatePostsRequest $request)
{
$image = $request->image->store('posts');
//create the posts
$post = Post::create([
'image' => $image,
'category_id' => $request->category,
'organizer' => $request->organizer,
'title' => $request->title,
'place' => $request->place,
'map' => $request->map,
'date' => $request->date,
'published_at' => $request->published_at,
'description' => $request->description
]);
if($request->tags) {
$post->tags()->attach($request->tags);
}
return redirect(route('posts.index'));
}
post.php
public function category()
{
return $this->belongsTo(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
帖子表
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image');
$table->integer('category_id');
$table->string('organizer');
$table->string('title');
$table->string('place');
$table->string('map');
$table->date('date');
$table->timestamp('published_at')->nullable();
$table->text('description');
$table->timestamps();
});
类别表
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
标签表
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
结果控制器.php
public function show($id,Post $post)
{
$post= Post::find($id);
$category = Category::find($id);
$tag = Tag::find($id);
return view('posts.show',compact('post'));
}
show.blade.php
Category: "I want to show category name here !"
<div class="tag-group">
Tags:
<div class="tags">
"I want to show tag's name here !"
</div>
</div>
解决方案
- 使用数据透视表“post_tag”表名创建迁移;详情在这里
- 在“posts”表的迁移中,请更改 $table->unsignedBigInteger('category_id');
- 调整你的控制器。您可以使用 $post->category 或 $post->tags;
推荐阅读
- html - 垂直对齐和 CSS 网格关系
- html - 如何传递来自soap xml的rgb值将其转换为xsl并传递rgb值
- r - 如何激活调试器或访问 Jupyter 笔记本中的日志?
- node.js - 用于字符串分类的张量流与弹性搜索
- jquery - Jquery AJAX - iRail API liveboard 错误
- python - 测试值是否包含在具有混合类型的 Pandas 系列中
- c# - 调试 WebMethod()s - 从调用项目中单步执行代码
- python - 如何用发票ID替换Odoo 8中的发票编号序列
- javascript - jsx 中 SVG 中道具的正确语法
- data-structures - 支持在 O(1) 中查找 2 个索引之间的最大数的数据结构