Cristian
Cristian

Reputation: 2550

Adjacency List Model for User Types

I have a fairly large number of user types that I need in my database and so far the only good option that does not involve lots and lots of tables is to use Adjacency List Model. Basically, my users are first split between the following types: Business, Individual and Administrator. From there it goes like this:
enter image description here

Note: I currently have 3 Levels of user types but this might change over time depending on business needs.

All my users share a common users table which holds details such as email, password, first name, last name, etc. All my business users have a separate businesses table which stores business specific data. The businesses users don't all share the same fields, but since I only need a few fields for each different type of user I thought it might be the best approach to have all the fields into one table and store NULL for the fields I don't use.

Now, I have this simple scenario. All my users have an user profile page. My business users have a business profile page as well. My Business-Technicians must have another page specific to them. Imagine a Computer Technician logs in. I want to be able to display a link for a Profile Page, Business Profile Page, and a Technician Dashboard.

To get a user type I have my model setup so that I can retrieve a "child" or "parent". If I say:

$user = new User::find(11);
$userType = $user->userType; //(relation set in the UserType & User Models)
while($userType != NULL) {
   dump($userType->name);
   $userType = $userType->parent; //(relation set in UserType Model)

}
// dump result:
// 11 - Computer Technician
// 5 - Technicians
// 1 - Business

How can I easily implement a way to check for Technicians (to provide the link for the Technician Dashboard) and to also check for Businesses (to provide the Business profile page link)?

Upvotes: 2

Views: 1565

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

I've created a package that uses common table expressions (CTE) to implement recursive relationships: https://github.com/staudenmeir/laravel-adjacency-list

You can use the ancestorsAndSelf relationship to check for specific user types:

class UserType extends Model
{
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;
}

$user = User::find(11);

$userTypes = $user->userType->ancestorsAndSelf;

if ($userTypes->where('name', 'Technicians')->isNotEmpty()) {
    //
}

if ($userTypes->where('name', 'Business')->isNotEmpty()) {
    //
}

Upvotes: 4

Related Questions