красноречивый laravel 5.8: имеет много отношений модель - PullRequest
0 голосов
/ 27 сентября 2019

Я создаю информационную систему событий и хочу показать теги в posts / 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();
    });

таблица create_categories

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

таблица create_tags

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>

Ответы [ 2 ]

2 голосов
/ 27 сентября 2019

$post->tags должен возвращать коллекцию, поэтому свойства отсутствуют name.

Ваш код show.blade.php должен быть:

<div class="tags">
    @foreach($post->tags as $tag)
        {{ $tag->name }}
    @endforech
</div>
2 голосов
/ 27 сентября 2019

В соответствии с вашими определенными отношениями post has many tags, поэтому вы не можете получить прямой доступ к one to many relationship, вам может потребоваться loop, чтобы получить подробную информацию о теге, например, имя

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

Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...