|
<?php |
|
/* |
|
These are some examples of how you can retrieve models filtered by |
|
some criteria on related models. For example, using the following set |
|
of tables and relations, you can get all user profiles for users who |
|
have a Member role. |
|
|
|
Users ∞ <-> ∞ Roles |
|
Users 1 -> ∞ Profiles |
|
Profiles 1 -> ∞ PortfolioItems |
|
|
|
In Laravel 5.5+ there are a couple of ways to do this. Speed and internal |
|
efficiency aside, I prefer this first method. It assumes you have a |
|
belongsTo() relation on your Profile model called 'user' that returns |
|
the User model for the current Profile. This also assumes you have a |
|
belongsToMany() relation on your User model called 'roles' that returns |
|
the all the Role models for which there is a relation. |
|
|
|
Notes: |
|
- I have left out namespaces for clarity |
|
*/ |
|
|
|
class Role { |
|
public function users() { |
|
return $this->belongsToMany('User'); |
|
} |
|
} |
|
|
|
class User { |
|
public function roles() { |
|
return $this->belongsToMany('Role'); |
|
} |
|
|
|
public function profiles() { |
|
return $this->hasMany('Profile'); |
|
} |
|
} |
|
|
|
class Profile { |
|
public function user() { |
|
return $this->belongsTo('User'); |
|
} |
|
|
|
public function portfolioItems() { |
|
return $this->hasMany('PortfolioItem'); |
|
} |
|
|
|
public function scopeProfilesOfMembers ( $query ) { |
|
return $query->whereHas('user', function( $userquery ) { |
|
$userquery->whereHas('roles', function( $rolesquery ) { |
|
$rolesquery->where('name', 'Member'); |
|
}); |
|
}); |
|
} |
|
} |
|
|
|
class PortfolioItem { |
|
public function roles() { |
|
return $this->belongsTo('Profile'); |
|
} |
|
} |
|
|