2017-02-04 90 views
1

我有如下表一对多的关系:许多与Laravel

帖子{id, title, description}

标签{id, name, description}

post_tags {post_id, tag_id}

在Laravel我已经建立了关系如下图所示。我不知道如何查询我的post_tags数据透视表。我得到的错误:

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'); 
} 

邮政型号:

public function tag() 
{ 
    return $this->belongsToMany('App\Tag'); 
} 

回答

1

您不需要为数据透视表添加模型(但您可以),而且您也不需要将数据库id添加到数据透视表。

你的关系是好的,但如果你想使用id,你应该添加withPivot('id')的关系

public function post() 
{ 
    return $this->belongsToMany('App\Post')->withPivot('id'); 
} 
+0

我不明白:?如果没有这个转换('id'),我的三张桌子就够了吗? – steven

+0

@steven是的,三个表格,两个模型。 –

+0

啊我现在明白了。谢谢:) – steven