我有3张表
1.的文章
2.类别
3. category_post .
My Posts Tables here:
+------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
| slug | varchar(255) | NO | | NULL | |
| reporter | varchar(255) | NO | | NULL | |
| meta | varchar(255) | NO | | 0 | |
| body | text | NO | | NULL | |
| image | varchar(255) | NO | | 0 | |
| top | tinyint(1) | NO | | 0 | |
| post_count | int(11) | NO | | 0 | |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 | |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+------------+------------------+------+-----+---------------------+----------------+
My Categories Table Here:
+---------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| category_slug | varchar(255) | NO | | NULL | |
| parrent_id | int(11) | NO | | 0 | |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 | |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+---------------+------------------+------+-----+---------------------+----------------+
My category_post table:
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| category_id | int(10) unsigned | NO | MUL | NULL | |
| post_id | int(10) unsigned | NO | MUL | NULL | |
+-------------+------------------+------+-----+---------+----------------+
我可以创建多个类别选择的帖子。但是当我想按类别显示帖子时,我无法访问类别表。这意味着,我想查看类别名称与每个帖子。
这是我的模型:
类别模型:
public function posts()
{
return $this->belongsToMany('Post');
}
In Post Model:
public function categories()
{
return $this->belongsToMany('Category');
}
My Query Helper function for Post by category:
public static function cat_post($category, $limit, $top)
{
$posts = Post::whereHas('categories', function($q) use ($category, $top)
{
$q->where('name', 'like', $category);
$q->where('top', 'like', $top);
})->with('categories')->take($limit)->orderBy('created_at', 'DESC')->get();
return $posts;
}
我可以查看所有的post数据。但类别名称不是。
My Post Loops:
<?php $headline = Helper::head_post(10, 1); ?>
@foreach ($headline as $post)
<li><a href="">{{ $post->title }}</a></li>
@endforeach
当我尝试这个类别名称不工作时:
@foreach ($headline as $post)
<li><a href="">{{ $post->categories->name }}</a></li>
@endforeach
请帮帮我。
因为这是一个多对多关系,$post->categories->name
将不起作用。它不知道你想要的是(众多类别中的)哪个类别的名称。
例如,您可以使用$post->categories()->first()->name
来获得第一个类别的名称,或者循环它们以获得所有类别的名称。