首页 > 解决方案 > 在数据透视表中我存储了 post_id 和 category_id 如何从数据透视表中获取我的帖子类别名称?

问题描述

这是我的类别模型


    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Category extends Model
    {
      public function posts()
      {
          return $this->belongsToMany('App\Post')->withTimestamps();
      }
    }

这是我的帖子模型


    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Post extends Model
    {
      public function categories()
      {
          return $this->belongsToMany('App\Category')->withTimestamps();
      }
      public function tags()
        {
            return $this->belongsToMany('App\Tag')->withTimestamps();
        }
      public function user()
       {
           return $this->belongsTo('App\User');
       }
    }

这是我的索引功能


    public function index()
        {
          $posts=Post::latest()->get();
          return view('admin.post.index',compact('posts'));
        }

这是我的查看页面

      @foreach($posts as $post)
         <tr>
               <td>{{ $post->id }}</td>
               <td>{{ str_limit($post->title,'10') }}</td>
               <td>{{$post->categories->pivot->name}}</td>
         </tr>
       @endforeach

当我想回显我的类别名称时,laravel 给了我这个错误。

此集合实例上不存在 ErrorException (E_ERROR) 属性 [pivot]。(查看:C:\xampp\htdocs\Advanced_Blog_System\resources\views\admin\post\index.blade.php)

我只需要查看类别名称我该如何解决这个问题???

标签: phplaravelpivot-table

解决方案


Post 和 Category 都具有多对多的关系,因此您需要另一个 foreach 类别;

@foreach($post->categories as $category)
    {{$category->name}}
@endforeach

推荐阅读