I have two models, User and Community. A user can belong to many communities while a community can have many users. I have implemented many-to-many relationship for this in both models and then created a pivot table communities_users. In Community Model, i have the users(members) relationship defined:
public function users(){
return $this->belongsToMany('AppUser', 'communities_users', 'community_id', 'user_id');
}
In User model, i have communities relationship defined as:
public function communities(){
return $this->belongsToMany('AppCommunity', 'communities_users', 'user_id', 'community_id');
}
I am able to call these relationships fine. No problems.
However, i need to add an admin_id on my communities table, representing the user that created the community (pointing to the same User model). I know this will be a belongsTo relationship in Community model and a hasMany relationship in User. I have added an admin_id column to my communities table. In my Community model, i have added my admin model like so;
public function admin(){
return $this->belongsTo('AppUser', 'admin_id');
}
If i try returning this, the app keeps breaking with a 500 Internal server error. How can i correct this and get it to return the user object that created the community?
2
Answers
I think let’s complete this database together from scratch
Your database as I understand it is as follows (part of it of course)
!! But if I don’t understand, changing the relationship will solve the problem
Step 1:
In user migration, use ForeignId to define community_id
Step 2:
Use has Many and belongs_To in your model
Model User
Model Community
You can do the same for the admin model
!! If I didn’t understand correctly, you can change the above connections, but the general work is the same as above
The second parameter that the belongsTo method takes is foreign_key!
in Community model:
in User model: