2017-09-06 28 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

あなたがチェックピボットtabelと外部キーのdocumentation

class Post extends Model 
{ 
.... 

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

} 
+1

あなたは男です!私はポストが多くのタグを持つことができ、タグが多くのポストに属しているので意味があると思った。私はそれが許せば私は受け入れるだろう。ありがとう – user3574492

1

両方の関係のためにbelongsToManyを使用する必要があります

クラス投稿モデル { ....

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

}

1

名がモデルで定義されている必要があり、あなたのポストモデルでbelongsToManyを使用する必要があります

class Post extends Model 
{ 
    .... 

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

}