【问题标题】:laravel 5.8 eloquent: has many relations modellaravel 5.8 eloquent:有很多关系模型
【发布时间】:2019-09-27 04:22:12
【问题描述】:

我正在创建活动信息系统并希望在帖子/show.blade.php 中显示标签。

但我遇到了一个错误。

此集合实例上不存在属性 [名称]

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

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

如何在 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());
    }

tag.php

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

category.php

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

create_posts_table

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'));
}

show.blade.php

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

【问题讨论】:

    标签: php mysql laravel laravel-5 eloquent


    【解决方案1】:

    根据您定义的关系post has many tags,因此您无法直接访问one to many relationship,您可能必须通过loop 获取标签详细信息,例如名称

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

    谢谢。

    【讨论】:

      【解决方案2】:

      $post-&gt;tags 应该返回一个集合,因此没有属性 name

      您的show.blade.php 代码应该是:

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

      【讨论】:

      • 你的答案和我的有什么不同?
      • @SalmanZafar 并没有什么不同。我们刚刚同时发布。
      • 如果没有新内容要添加,最好避免重复发布相同的答案
      猜你喜欢
      • 2015-08-05
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 2021-10-01
      • 2018-10-20
      • 2021-07-04
      相关资源
      最近更新 更多