gabordemooij / redbean

ORM layer that creates models, config and database on the fly
https://www.redbeanphp.com
2.31k stars 279 forks source link

RedBeanPHP: how to add timestamp, unique default? #567

Closed elieobeid7 closed 7 years ago

elieobeid7 commented 7 years ago

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

$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')));
Lynesth commented 7 years ago

Hello,

Regarding the defaults, it is not possible using RedBean functions.

You either have to change the column properties in your database (remove the fact that it can be NULL and set a default value of your choice) or you have to check beforehand (in PHP I mean) and modify the value accordingly before storing your bean.

Regarding the unique index, you can do this :

$user = R::dispense('user');
$user->setMeta('sys.uniques', array('email')); /* can be removed afterwards */
$user->fname = 'Bob';
$user->lname = 'Sponge';
$user->email = 'bs@deepinthe.sea';
R::store($user);
?>

This way, the email field will be unique in your database. This does not mean that RedBean will check it for you when you create a new user, as it will simply raise a database exception.

You could also simply set the unique index directly in your database manager (like phpmyadmin).

Lyn.