与 Laravel 的多对多关系
Many to Many relationship with Laravel
我有以下 tables:
Posts {id, title, description}
标签{id, name, description}
post_tags {post_id, tag_id}
在Laravel中我建立了如下关系。我不确定如何查询我的 post_tags 数据透视表 table。我收到以下错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dev_match.post_tag' doesn't exist (SQL: select `tags`.*, `post_tag`.`post_id` as `pivot_post_id`, `post_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`post_id` = 1)
家庭控制器:
public function getindex(){
$post = Post::all();
return view('welcome', compact('post'));
}
主视图:
@foreach($post as $posts)
<tbody>
<tr>
<td> <a href="">{{$posts->tags->name}}</a> </td>
<td> </td>
<td> asked </td>
</tr>
</tbody>
@endforeach
标签模型:
public function post()
{
return $this->belongsToMany('App\Post');
}
Post 型号:
public function tag()
{
return $this->belongsToMany('App\Tag');
}
您不需要为枢轴添加模型 table(但您可以),而且您不需要为枢轴添加模型 id
table.
你的关系没问题,但如果你想使用id
,你应该在关系
中添加withPivot('id')
public function post()
{
return $this->belongsToMany('App\Post')->withPivot('id');
}
我有以下 tables:
Posts {id, title, description}
标签{id, name, description}
post_tags {post_id, tag_id}
在Laravel中我建立了如下关系。我不确定如何查询我的 post_tags 数据透视表 table。我收到以下错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dev_match.post_tag' doesn't exist (SQL: select `tags`.*, `post_tag`.`post_id` as `pivot_post_id`, `post_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`post_id` = 1)
家庭控制器:
public function getindex(){
$post = Post::all();
return view('welcome', compact('post'));
}
主视图:
@foreach($post as $posts)
<tbody>
<tr>
<td> <a href="">{{$posts->tags->name}}</a> </td>
<td> </td>
<td> asked </td>
</tr>
</tbody>
@endforeach
标签模型:
public function post()
{
return $this->belongsToMany('App\Post');
}
Post 型号:
public function tag()
{
return $this->belongsToMany('App\Tag');
}
您不需要为枢轴添加模型 table(但您可以),而且您不需要为枢轴添加模型 id
table.
你的关系没问题,但如果你想使用id
,你应该在关系
withPivot('id')
public function post()
{
return $this->belongsToMany('App\Post')->withPivot('id');
}