php - laravel 5.8 Eloquent : has many relations model

标签 php mysql laravel laravel-5 eloquent

我正在创建事件信息系统并希望在 posts/show.blade.php 中显示标签。

但是我得到一个错误。

Property [name] does not exist on this collection instance

在帖子表中,我有 category_id。 我创建了 post_tag 表。

我需要创建另一个新表吗?

How to show tags in show.blade.php ?

请帮帮我。

post.php

   public function tags() 
{
    return $this->belongsToMany(Tag::class);

}
public function hasTag($tagId)
    {
        return in_array($tagId, $this->tags->pluck('id')->toArray());
    }

标签.php

public function posts()
{
    return $this->belongsToMany(Post::class);
}

类别.php

public function posts()
{
    return $this->hasMany(Post::class);
}

创建帖子表

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image');
        $table->unsignedBigInteger('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();
    });

post_tag 表

Schema::create('post_tag', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('post_id');
        $table->integer('tag_id');
        $table->timestamps();
    });

ResultsControllere.php

public function show($id,Post $post)
{
    $post= Post::find($id);
    $post->category;
    $post ->tags;
    return view('posts.show',compact('post'));
}

显示.blade.php

Tags:
  <div class="tags">
     {{ $post->tags->name }}
 </div>

最佳答案

根据你定义的关系post有很多标签所以你不能直接访问一对多关系你可能必须循环通过获取标签详细信息,例如名称

<div class="tags">
     @foreach($post->tags as $tag)
     {{ $tag->name }}
     @endforeach
</div>

谢谢。

关于php - laravel 5.8 Eloquent : has many relations model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127847/

相关文章:

php - 谷歌地图 API v3 : How to Set Zoom Level And Map Center To User Submitted Location?

javascript - PHP 重新排列数组并按值分组

PHP通过特定键过滤二维数组

php - PHP : How to first log an exception and then report by mail?

php回显不显示

MySQL - 我可以避免这些相关/依赖子查询吗?

php - Mysql根据一张表的ID从2张表中选择数据

php - undefined variable : errors -- Laravel 5. 2

php - 在 laravel 5.4 中选择下拉列表的选定值

javascript - 自定义帖子类型 - 类别添加按钮不起作用