2017-09-06 81 views
0

我有一個基本的多對多的關係:Laravel多對多不工作

Posts 
Tags 

我有一個數據透視表名爲post_tag

我想TOR回報都在我的視圖文件給定的帖子標記爲這樣:

@foreach($posts as $post) 

    {{ dd($post->tags) }} 

@endforeach 

我收到以下錯誤:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.post_id' in 'where clause' (SQL: select * from tags where tags . post_id = 1 and tags . post_id is not null) (View: C:\wamp\www\laravel\resources\views\posts\index.blade.php)

這裏是我的模型:

class Post extends Model 
{ 
    .... 

    public function tags() { 
     return $this->hasMany(\App\Models\Tag::class); 
    } 

} 


class Tag extends Model 
{ 
    .... 

    public function posts() { 
     return $this->belongsToMany(\App\Models\Post::class); 
    } 

} 

關於這裏發生了什麼的任何想法?我在數據透視表中有數據,但好像關係不正常。

回答

2

您應該使用belongsToMany兩個關係

class Post extends Model 
{ 
    .... 

    public function tags() { 
     return $this->belongsToMany(\App\Models\Tag::class); 
    } 

} 
+1

你是男人!我認爲這是有道理的,因爲Post可以擁有許多標籤和一個Tag屬於許多帖子。我會接受,當它讓我。謝謝 – user3574492

1

你應該張貼模型中使用belongsToMany,檢查支點TABEL和外鍵的documentation

class Post extends Model 
{ 
.... 

    public function tags() { 
     return $this->belongsToMany(\App\Models\Tag::class); 
    } 

} 
1

名稱必須在模型

定義

class Post延伸型號 { ....

public function tags() { 
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','tag_id',post_id); 
} 

}

類的標籤擴展型號 { ....

public function Posts() { 
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','post_id',tag_id); 
} 

}