首页 文章

与Laravel的多对多关系

提问于
浏览
1

我有以下表格:

帖子 {id, title, description}

标签 {id, name, description}

post_tags {post_id, tag_id}

在Laravel我 Build 了如下关系 . 我不知道如何查询我的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 回答

  • 1

    您不需要将 id 添加到数据透视表 .

    你的关系没问题,但是如果你想使用 id ,你应该将withPivot('id')添加到关系中

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

相关问题