我的数据库中有3个表:
id
,title
)id
,name
),post_id
,categories_id
)。我正在使用 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
关系。