Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsTo and hasMany relationship on same model

Tags:

laravel

How do you apply belongsTo and hasMany relationship on same model?

For example, I have one User and one Project model. Now Project model has method user() and User model has projects() method.

Now I want a user to share projects with other users. So that I can have methods like users() in Project model and shared_projects() in User model.

How I can achieve that?

Here is my current Project model

class Project extends \Eloquent {
    protected $fillable = [];

    public function user() {
        return $this->belongsTo('User');
    }
}

And this my User model

class Project extends \Eloquent {
    protected $fillable = [];

    public function projects() {
        return $this->hasMany('Project');
    }
}
like image 878
virajzaveri Avatar asked Sep 06 '25 03:09

virajzaveri


2 Answers

In this case, User and Project have Many-to-Many relationship because one user has many projects and one project belongs to many user. Therefore, you should create a third table (project_user) which connect User table and Project table in the database. And you set Many-to-Many relation to User Model and Project Model.

class User extends Eloquent {

public function projects()
{
    return $this->belongsToMany('Project');
}

}

In Project model

class Project extends Eloquent {

public function users()
{
    return $this->belongsToMany('User');
}

}

Then you can do something like this

//users in the same project
$users = Project::find($id)->users;
like image 181
Phi Nguyen Avatar answered Sep 07 '25 21:09

Phi Nguyen


Okay, so here it is how I solved it. I used pivot table as you suggested but I even added hasMany relationship like this way. I am still not sure what I am doing is perfectly correct but it worked. :)

class Project extends \Eloquent {
    protected $fillable = [];

    public function users() {
        return $this->belongsToMany('User');
    }

    public function user() {
        return $this->belongsTo('User');
    }
}

And here is the key ingredient in User model

class User extends \Eloquent {
    protected $fillable = [];

    public function projects_owned() {
        return $this->hasMany('Project', 'user_id');
    }

    public function projects() {
        return $this->belongsToMany('Project');
    }
}
like image 24
virajzaveri Avatar answered Sep 07 '25 21:09

virajzaveri