I need to create a feature of user following. So I could let users follow each other. This require a pivot table right? but how do I do it if the users are all from the same table?
Your table that stores the follower/following relationships should have two fields that each store a user id...
Something like this:
follows
- followed_id (references User ID of user being followed)
- follower_id (references user ID of the user who is following that user)
Then in your user model you'd have something like this:
public function followers() {
return $this->belongsToMany('User', 'follows', 'followed_id', 'follower_id');
}
public function following() {
return $this->belongsToMany('User', 'follows', 'follower_id', 'followed_id');
}
I do have that pivot table you're talking about. here's the migration if it:
{
Schema::table('follower_followee', function (Blueprint $table)
{
$table->integer('follower_id')->unsigned(); // follower id number,must be positive.
$table->integer('followee_id')->unsigned(); // followee id number,must be positive.
$table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
//The 'follower_id' column references to the 'id' column in a 'users' table.
//When a user is deleted in the parent column ('follower_id'), then also the user in 'id' ('users') is deleted.
$table->foreign('followee_id')->references('id')->on('users')->onDelete('cascade');
});
}
Now should I remove the Followee.php model then (after updating the User model)?
what's the 'User' and 'follows' arguments are for?
Edit: so far I assume 'User' is the model name. And 'follower_id', 'followed_id' are the table columns. But what's 'follows' and does it all work together?
Hi @willvincent sir, I can not add values in pivot table. Please guide me!
My scenario is like:
model: Category
There can be multiple sub categories of the single main category, hence there is a many to many relationship.
Like a Mobile is main category the sub-category would be samsung, iphone. and like iphone is also a Apple Brand and as well as a Mobile. Many to many. The above steps are great. But I can't add values in pivot table named "categories_parent"