2013-05-29 6 views
0

내 게시물과 범주 모델간에 다 대다 관계를 사용하려고합니다. 지금까지 게시물, 카테고리 및 post_categories 테이블을 만들었습니다. 양식을 제출하면피벗 테이블이 예상대로 작동하지 않습니다.

$post = new Post; 

     $post->title   = e(Input::get('title')); 
     $post->slug    = e(Str::slug(Input::get('title'))); 
     $post->content   = e(Input::get('content')); 
     // Was the blog post created? 
     if($post->save()) 
     { 
      $id = (int) Input::get('category_id'); 
      $category = Category::find($id); 

      $post->categories()->attach($category); 
      // Redirect to the new blog post page 
      return Redirect::to("admin/blogs/$post->id/edit")->with('success', Lang::get('admin/blogs/message.create.success')); 
    } 

내가 블로그 게시물은 볼 수 있습니다 : 나는 의해 게시 인스턴스를 만들려고 할 때 내 모델에서

, 내 관계

class Post extends Eloquent { 
    public function categories() 
    { 
     return $this->belongsToMany('Category', 'post_categories','category_id'); 
    } 
} 
class Category extends Eloquent { 
    public function posts() 
    { 
     return $this->belongsToMany('Post','post_categories'); 
    } 
} 

내 컨트롤러에이 정상적으로 생성되었습니다. db를 확인하면 category_id가 post_categories 테이블에 삽입되지만 post_id는 항상 0입니다.

누구든지 해결하도록 도움을 줄 수 있습니까?

답변

0

잘못된 방식으로 관계를 사용하고있었습니다. 테이블은 두 번째 테이블 열 이름을 알아야했습니다.

class Post extends Eloquent { 
    public function categories() 
    { 
     return $this->belongsToMany('Category', 'post_categories','category_id','post_id'); 
    } 
} 
class Category extends Eloquent { 
    public function posts() 
    { 
     return $this->belongsToMany('Post','post_categories',,'post_id','category_id'); 
    } 
} 

가장 좋은 사용법은 테이블 이름을 변경하고 category_post 테이블로 변경하는 것입니다. 이렇게해야 할 일은 모두

class Post extends Eloquent { 
    public function categories() 
    { 
     return $this->belongsToMany('Category'); 
    } 
} 
class Category extends Eloquent { 
    public function posts() 
    { 
     return $this->belongsToMany('Post'); 
    } 
} 
입니다.
0
$post->categories()->attach($category->id); 
관련 문제