首页 > 解决方案 > 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>

标签: phpdatabaselaravellaravel-5information-retrieval

解决方案


  1. 使用数据透视表“post_tag”表名创建迁移;详情在这里
  2. 在“posts”表的迁移中,请更改 $table->unsignedBigInteger('category_id');
  3. 调整你的控制器。您可以使用 $post->category 或 $post->tags;

推荐阅读