Custom table name for a model in laminas

155 Views Asked by At

I've started learning laminas by reading it's documentation (Album model and table). I have a product model and I want to fetch the records but the problem is that the name of my table is tbl_product and I get this error:

Statement could not be executed (42S02 - 1146 - Table 'project.product' doesn't exist)

Where can I define the table name?

1

There are 1 best solutions below

0
On BEST ANSWER

Supposing that by "reading it's documentation" you are talking about Laminas' tutorial, then the answer can be found under the the Database and Models section

When you define a new model, you must update the module's configuration, specifying where the application will find the model's factory and gateway:

// Add this method:
public function getServiceConfig()
{
    return [
        'factories' => [
            Model\AlbumTable::class => function($container) {
                $tableGateway = $container->get(Model\AlbumTableGateway::class);
                return new Model\AlbumTable($tableGateway);
            },
            Model\AlbumTableGateway::class => function ($container) {
                $dbAdapter = $container->get(AdapterInterface::class);
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Model\Album());
                return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
            },
        ],
    ];
}

The class that contains the db table information is TableGateway, which constructor is:

public function __construct(
    $table,
    AdapterInterface $adapter,
    $features = null,
    ?ResultSetInterface $resultSetPrototype = null,
    ?Sql $sql = null
)

The first parameter is the table's name.
Hence, in your configuration, you need something like:

Model\ProductTable::class => function($container) {
    $tableGateway = $container->get(Model\ProductTableGateway::class);
    return new Model\ProductTable($tableGateway);
},
Model\ProductTableGateway::class => function ($container) {
    $dbAdapter = $container->get(AdapterInterface::class);
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new Model\Product());
    return new TableGateway('tbl_product', $dbAdapter, null, $resultSetPrototype);
},