This might be very simple, but I can't find the solution... Any help will be appreciated. I have 3 tables: users, skills and projects, all connected to each other with Many to Many relationship.
User model
public function skills()
{
return $this->belongsToMany('Skill')->withPivot('level');
}
public function projects(){
return $this->belongsToMany('Project')->withPivot('user_id', 'project_id');
}
Skill model
public function users() {
return $this->belongsToMany('User')->withPivot('level');
}
public function projects() {
return $this->belongsToMany('Project')->withPivot('level');
}
Project model
public function users(){
return $this->belongsToMany('User')->withPivot('user_id', 'project_id');
}
public function skills(){
return $this->belongsToMany('Skill')->withPivot('level');
}
So, a Many to Many triangle. I want to get all the projects, the skills of which are subset of specific users skills. So basically "suggested projects" for user.
$projects = Project::whereHas('skills', function($q) use($array)
{
$q->thatAreSubsetOf($array);
//$array contains names or ids of users skills
})->orderBy('created_at', 'DESC')->get();
If some $user->skills
are 'PHP', 'C' and 'Javascript', all the returned projects skills should only be subset of those (e.g. {'PHP', 'C'} or {'PHP', 'Javascript'} or {'Javascript', 'C'} or {'PHP', 'C', 'Javascript'} or {'PHP'}, or {'Javascript'} or {'C'}) I've tried many thing, researched a lot in Laravel Docs/here but can't seem to get what I want..
Basically your requirement can achieve Many To Many Polymorphic Relations
. Your requirement is to use skills with User and Project, so its would be easy to handle with MTMPR
.
Example below shows how I have implemented sharing Skill with both Project and User.
DB Schema
Skill
id integer
name string
skillable
id integer
skillable_id integer
skillable_type string
Models
Skill
class Skill extends Eloquent{
public function projects(){
return $this->morphedByMany('Project', 'skillable');
}
public function users(){
return $this->morphedByMany('User', 'skillable');
}
}
Project
class Project extends Eloquent{
public function skills(){
return $this->morphToMany('Skill', 'skillable');
}
}
User
class User extends Eloquent{
public function skills(){
return $this->morphToMany('Skill', 'skillable');
}
}
How to get skill from project
$project = Project::find($id);
$projectsSkill = $project->skills()->all();
And how you can get Project from skills
$skill = Skill::find(1);
$projects = $skill->projects();
If you still find something unclear to handle these situation, let me know.