Search code examples
phpmariadbredbean

RedBean PHP setMeta(...) for UNIQUE keys not working


I'm using 5.1.0 with and .

I'm trying to get one bean attribute (or column in the database) to be set as UNIQUE just using RedBeanPHP.

According RedBeanPHP official docs, and many Google and StackOverflow articles, the solution is to use the function setMeta(...) but unfortunately it's not working.

This is the code I wrote to test my problem.

<?php

include 'rb.php';
R::setup('mysql:host=localhost;dbname=test', 'root', '');

R::nuke();

// =====================================

$bean = R::dispense('bean');
$bean->name = 'any';

$bean -> setMeta('buildcommand.unique', array(array('name')) );
R::store($bean);  // No problem here. As expected :-)

// =====================================

$another_bean = R::dispense('bean');
$another_bean->name = 'any';

R::store($another_bean); // it works !!, but it shouldn't. Exception expected :-(

?>

I've also tried, according to another google hits, other options for setMeta(...), although I think they're deprecated. anyway they also don't work.

$bean -> setMeta('buildcommand.unique.0', array('name') );

... also with ...

$bean -> setMeta('sys.uniques', array('name') );

...and many like these ones. Also tried to use another schema (not "test"). I thought it was maybe related to the lack of privileges to do an "ALTER TABLE", but it didn't

Also activated a...

R::debug(true)

... but I don't see RedBeanPHP trying to do an "ALTER TABLE" at all.

Thanks for your help


Solution

  • Sorry, but build commands are no longer supported since version 4.2.0 as stated here https://redbeanphp.com/index.php?p=/changelog

    If your requirement does not allow to set the attribute to unique within your database, you may introduce a model and check for uniqueness of the attribute yourself.

    class Model_Book extends RedBean_SimpleModel
    {
        public function update()
        {
            if (!$this->bean->getId()) {
                if (R::findOne("book", "name = ?", array($this->bean->name))) {
                    throw new Exception('Book with name ' . $this->bean->name . ' already exists');
                }
            }
        }
     }