Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Model relationship directly with the name of the table in the database

Hi,

In order to create an access management system, I have multiple roles into my application and these roles can have multiple modules as well.

Here is my current relationship model:

class Roles extends Model
{
    public function initialize()
    {
        $this->hasManyToMany(
            'id',
            'RolesModules',
            'role_id',
            'module_id',
            'Modules',
            'id',
            [
                'alias' => 'modules'
            ]
        );
    }
}
class RolesModules extends Model {}
class Modules extends Model {}

And here are my tables:

CREATE TABLE `modules` (
  `id` TINYINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `active` BOOLEAN NOT NULL DEFAULT TRUE,
  `name` VARCHAR(30) NOT NULL UNIQUE,
  `controller` VARCHAR(30) NOT NULL UNIQUE,
  `icon` VARCHAR(20) NOT NULL,
  `has_subfolder` BOOLEAN NOT NULL DEFAULT FALSE,
  `parent_id` TINYINT UNSIGNED DEFAULT NULL,
  CONSTRAINT `fk_modules_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `modules`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `roles` (
  `id` TINYINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `name` VARCHAR(40) NOT NULL UNIQUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `roles_modules` (
  `id` SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `role_id` TINYINT UNSIGNED NOT NULL,
  `module_id` TINYINT UNSIGNED NOT NULL,
  CONSTRAINT `fk_roles_modules_role_id` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`),
  CONSTRAINT `fk_roles_modules_module_id` FOREIGN KEY (`module_id`) REFERENCES `modules`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

it works perfectly but I still have a question:

Is it possible to delete the class "RolesModules" and to indicate the table "roles_modules" directly in the "HasManyToMany" relation?



57.5k
Accepted
answer
edited Jun '18

No. ORM only works in a PHQL context, you cannot use raw syntax.

You could rename your class to match the table name.

Or, if your problem is namespaces, just use this format:

[\Some\Name\Space\]RolesModules::class instead of string literal. This has the benefit of IDE's being able to refactor class name changes automatically.



1.7k

Thank you Lajos Bencz.

You answered to my question perfectly, as always.

Hoping that my question and your answer can help others.