RedBean PHP setMeta(..) for UNIQUE keys 不起作用



我正在使用redbean 5.1.0和mariadb和php。

我正在尝试仅使用 RedBeanPHP 将一个 bean 属性(或数据库中的列(设置为唯一。

根据RedBeanPHP官方文档以及许多Google和StackOverflow文章,解决方案是使用该函数setMeta(...)但不幸的是它不起作用。

这是我为测试我的问题而编写的代码。

<?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 :-(
?>

根据另一个谷歌点击,我也尝试了setMeta(...(的其他选项,尽管我认为它们已被弃用。 无论如何,它们也不起作用。

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

。还用...

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

。许多人喜欢这些。还尝试使用另一个模式(不是"测试"(。我认为这可能与缺乏做"ALTER TABLE"的权限有关,但事实并非如此

还激活了...

R::debug(true)

。但我根本没有看到RedBeanPHP试图做一个"ALTER TABLE"。

感谢您的帮助

抱歉,自 4.2.0 版以来不再支持构建命令,如此处所述 https://redbeanphp.com/index.php?p=/changelog

如果您的需求不允许在数据库中将属性设置为唯一,则可以引入模型并自行检查属性的唯一性。

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');
            }
        }
    }
 }

最新更新