Search code examples
phpredbean

RedBeanPHP: how to add timestamp, unique and default?


I'm using the latest stable version, if I have to update for version 5, let me know.

<?php
$user = R::dispense('user');
$user->fname = 'man';
$user->lname = '00';
$user->setMeta("buildcommand.unique" , array($user->email='e@e.com'));
$user->pass = password_hash('password', PASSWORD_DEFAULT);

$user->gender=0; // I want this to have a default value of 0 if I don't insert anything
$user->verified=1;
$user->lastModified = date('Y-m-d G:i:s'); // I want this to be a timestamp, right now it's stored as datetime
$id= R::store($user);

lastModified is stored as datetime. I want gender and verified to have a default value of 0. I want email to be unique.

I tried every solution I could find on stackoverflow and nothing works

$user->setMeta("buildcommand.unique" , array(array('email')));

And how to create blob and how to specify a length for a field?


Solution

  • To preset values of your beans you should use the dispense method of your model class. See https://redbeanphp.com/index.php?p=/models

    For example to preset bean attributes you would write a model class like this:

    class Model_User extends RedBean_SimpleModel
    {
        public function dispense()
        {
            $this->bean->gender = 0;
            $this->bean->verified = 1;
        }
    }
    

    To make email an unique attribute you should'nt use RB meta function, but instead define the field as unique in your database.

    RB is designed to let you work on the business logic while in fluid mode and whenever your logic works, you have the option to freeze the complete database or partial tables as described here https://redbeanphp.com/index.php?p=/fluid_and_frozen.

    If RedBean isn't able to guess the datatype you want when in fluid mode it is also recommended to set the datatype manually.