skip to Main Content

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


  1. I think let’s complete this database together from scratch

    Your database as I understand it is as follows (part of it of course)

    enter image description here

    !! But if I don’t understand, changing the relationship will solve the problem

    Step 1:
    In user migration, use ForeignId to define community_id

    .
    .
    .
    $table->foreignId('community_id')->constrained();
    .
    .
    .
    

    Step 2:
    Use has Many and belongs_To in your model

    Model User

    public function communities(){
        return $this->hasMany(AppCommunity::class, 'community_id', 'id');
    }
    

    Model Community

    public function users(){
        return $this->belongsTo(AppUser::class, 'community_id', 'id');
    }
    

    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

    Login or Signup to reply.
  2. The second parameter that the belongsTo method takes is foreign_key!

    in Community model:

    public function admin(){
            return $this->belongsTo('AppUser'); //Laravel considers 'id' by default
        }
    

    in User model:

    public function  adminOfCommunities(){
            return $this->hasMany('AppCommunity', 'admin_id');
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search