从laravel 4.2中的hasManyThrough关系中检索数据的问题

时间:2015-03-30 07:53:17

标签: php laravel laravel-4 eloquent has-many-through

我的数据库中有3个表:

  1. 帖子包含(idtitle
  2. 类别(idname),
  3. categories_posts(post_idcategories_id)。
  4. 我正在使用 laravel 4.2 。这是我的模特:

    post.php中

    protected $table = 'posts';
    public function categories_posts()
    {
        return $this->hasMany('Categories_post', 'post_id');
    }
    
    public function categories()
    {
        return $this->hasManyThrough('Categories', 'Categories_post');
    }
    

    Categories.php

    protected $table = 'categories';
    
    protected $fillable = ['name', 'description'];
    
    public function categories_posts()
    {
        return $this->hasMany('Categories_post', 'categories_id');
    }
    
    public function posts()
    {
        return $this->hasManyThrough('Post', 'Categories_post');
    }
    

    Categories.php

    protected $table = 'categories_posts';
    
    protected $fillable = ['categories_id', 'post_id'];
    
    public function categories()
    {
    
        return $this->belongsTo('Categories');
    }
    
    public function posts()
    {
        return $this->belongsTo('Post');
    }
    

    PostsController.php

    public function index()
    {
        $posts = Post::with('author')->get();
        return View::make('posts.index', (
            'posts' => $posts);
    }
    

    很快就会出现主要代码 index.blade.php

    @foreach ($posts as $post)
      <tr>
       <td>{{ $post->created_at }}</td>
       <td>{{ $post->title }}</td>
       <td>{{ $post->author->display_name }}</td>
       @foreach ($post->categories->categories_post as $cat)
         <td>{{ $cat->name }}</td><!-- how to get category name associated with posts !>
       @endforeach
       <td>{{ $post->status }}</td>
       <td>{{ $post->comments_count }}</td>
      @endforeach
    

    该代码返回错误,我不明白。

    那么如何获得一个category名称,该名称与posts关系hasManyThrough相关。

    建议我是否有更好的方法,而不是使用hasManyThrough关系。

0 个答案:

没有答案