Tuesday, March 7, 2017

How can I collect all my types into one table in laravel?

I have got multiple type tables where I specify types of other tables. I use these types for form selections or other for use. For example I have a users table and a user_types. I have articles and article_types. I have images and image_types. But what I want is to use one table for all these and other tables. What relationship and system can I use for this?

users
id  name  surname  type
1   john  doe      1
2   jane  doe      2

user_types
id  title
1   Writer
2   Reader

articles
id  title  type  text
1   a man  1     a man is...
2   red B  3     there are ...

article_types
id  title
1   Story
2   News
3   Report

...

Here I can use the one to many relationship for users like:

class User extends Model
{
   public function type()
   {
       return $this->belongsTo(UserType::class);
   }
}

class UserType extends Model
{
   public function users()
   {
       return $this->hasMany(User::class);
   }
}

and now I can easily use:

$user = User::find(1);
$user->type()->title;

or simply get all types :

$userTypes = UserType::all();

But I want to gather all types into one table. Is there a way for that. Or should I better go with the old style?



via Skeletor

Advertisement