4
4
4sadly2020-06-22 12:29:38
PHP
4sadly, 2020-06-22 12:29:38

Eloquent orm, is it possible to make different entities in the same table?

Is it possible to use different entities depending on the type field in the users table, for example, if type = 0, then this is the Admin class, if 1, then User?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2020-06-22
@4sadly

Yes, you can. But I'm not sure if this is necessary in your case. I needed it because I had to work with an already existing table structure. I did this: The base class of the model, from which the other two are inherited. The base class has this structure:

protected static function boot()
{
  parent::boot();

  if (static::TYPE) {

    static::addGlobalScope('type_scope', function (Builder $builder) {

      $table = $builder->getModel()->getTable();

      $builder->where("{$table}.type", '=', static::TYPE);
    });
  }
}

In child classes, you need to define the TYPE constant and add the default type for a particular class to the $attributes property

A
Adamos, 2020-06-22
@Adamos

For the main entities represented by independent classes - it's not worth it, the headache will be more than good.
But for auxiliary ones (for example, for storing data attached to instances of different file classes) - it is used with might and main and is described in the documentation as Polymorphic Relationships.

S
Sanes, 2020-06-22
@Sanes

If the structure is the same, then why not? In your example, this is the user. The same can be true for post types (blog, news, etc.).
The essence is the same, but the types are different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question