【问题标题】:Many to Many relationship with Laravel与 Laravel 的多对多关系
【发布时间】:2017-06-21 20:13:42
【问题描述】:

我有以下表格:

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

【问题讨论】:

    标签: php laravel many-to-many relationship


    【解决方案1】:

    您无需为数据透视表添加模型(但您可以),而且您无需向数据透视表添加id

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

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

    【讨论】:

    • 我不明白:?。如果没有这个 withPivot('id'),我的三个表就够了吗?
    • @steven 是的,三个表,两个模型。
    • 啊我现在明白了。谢谢你:)
    • 您添加的最后一部分 - withPivot('id') 这是为了什么?另外,你说我不需要 post_tags 表的 id 吗?这是为什么?我只是好奇。
    • withPivot() 用于自定义列。如果您不想使用id,请不要使用wthPivot(),是的,您不需要将id 添加到数据透视表中。
    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2013-05-15
    • 2014-09-27
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    相关资源
    最近更新 更多