Let's clarify the relations first. So far, this is what we've got:
-
PostCategory-Post(many to one relation)- A PostCategory has zero or more Posts
- A Post belongs to one and only one PostCategory
If this is the intended relationship between these two entities then to update the relation you should:
// ...
$fooCategory = PostCategory::find($categoryId);
$myPost = Post::find($postId);
$fooCategory->posts()->save($myPost);
You have to add the posts relation in you PostCategory model, like this:
// app/models/PostCategory.php
class PostCategory extends Eloquent {
// ...
public function posts () {
return $this->hasMany('Post', 'post_category_id');
}
}
And your posts table should contain a post_category_id column as a foreign key representing the PostCategory id.
You have also to add the postCategory relation in you Post model, like this:
// app/models/Post.php
class Post extends Eloquent {
// ...
public function postCategory () {
return $this->belongsTo('PostCategory', 'post_category_id');
}
}
When you have to update a hasMany (Category has many Posts), then you use the save() method. When you have to go the other way, you use the associate() method.
Now, when you talk about categories, the usual is that this should most of the times be a Many to Many relation:
-
PostCategory-Post(many to many relation)- A PostCategory has zero or more Posts
- A Post belongs to zero or more PostCategory
But for this you'll need a relational table and some extra effort.
See more about relations at http://laravel.com/docs/4.2/eloquent#relationships