I have 3 tables in my Database:
- posts contains(
id, title)
- categories (
id, name),
- categories_posts (
post_id, categories_id).
I am using laravel 4.2. That are my Models:
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);
}
shortly presents main code
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
That code returns errors, I don't understand.
So how to get a category name, which is related to posts by hasManyThrough relation.
Suggest me if there is a better way, than make use of the hasManyThrough relation.