2017-02-04 58 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