W
W
WebDev2020-09-01 14:39:22
Laravel
WebDev, 2020-09-01 14:39:22

How to properly set up the relationship in this case?

I'm doing something like a page builder.
There is a page entity (page) to which modules can be added (Text, Image, Link, etc.).
Started the following entities:

//Страница
class Page extends Model
{
  public function modules()
  {
    return $this->hasMany(Module::class);
  }
}

//Модуль
class Module extends Model
{
  protected $fillable = [
    'page_id',
    'type',
    'order'
  ];

  public function texts()
  {
    return $this->hasMany(Text::class);
  }

  public function links()
  {
    return $this->hasMany(Link::class);
  }

  public function images()
  {
    return $this->hasMany(Image::class);
  }
}

//Модуль Текст
class Text extends Model
{
  protected $fillable = [
    'module_id',
    'text'
  ];
}

//Модуль Ссылка
class Link extends Model
{
  protected $fillable = [
    'module_id',
    'url',
    'name',
    'order'
  ];
}

//Модуль Картинка
class Image extends Model
{
  protected $fillable = [
    'module_id',
    'url',
    'name'
  ];
}

A person created a page, added a module of a certain type, and depending on the type, he sets up this module.
A module with type "text" has only a text field, a module with type "link" has a link, name and place in the queue, and so on.
But since the module has only one type, its relation will always be filled with only one, and the other two will be empty. Can you do something differently? For example, like this:
class Module extends Model
{
  protected $fillable = [
    'page_id',
    'type',
    'order'
  ];

  public function items()
  {
    if ($this->type === 'text') {
      return $this->hasMany(Text::class);
    } else if ($this->type === 'link') {
      return $this->hasMany(Link::class);
    } else if ($this->type === 'image') {
      return $this->hasMany(Image::class);
    }
  }
}


How to properly organize the structure for such a task?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question