Search code examples
phpormredbean

How to store an array() in a RedBean property?


I got the following:

$post = (array) json_decode($post);
$pushUser->dagen = (array) $post['days'];

The 'days' part of the post is:

[dagen] => Array
    (
        [0] => Monday
        [1] => Wednesday 
    )

All I want to do is store in $pushUser-dagen the array with days :)... pretty easy huh?

But then I get these errors:

exception 'RedBean_Exception_Security' with message 'Invalid Bean: property dagen ' in E:\Documenten\Dropbox\Dropbox\dummy-htdocs\VID_service\vid_push\libs\rb.php:3465 Stack trace: #0 E:\Documenten\Dropbox\Dropbox\dummy-htdocs\VID_service\vid_push\libs\rb.php(3496): RedBean_OODB->check(Object(RedBean_OODBBean)) #1 E:\Documenten\Dropbox\Dropbox\dummy-htdocs\VID_service\vid_push\libs\rb.php(7376): RedBean_OODB->store(Object(RedBean_OODBBean)) #2 E:\Documenten\Dropbox\Dropbox\dummy-htdocs\VID_service\vid_push\api\registerpush.php(32): R::store(Object(RedBean_OODBBean)) #3 {main}

Is it not possible to store arrays in a RedBean Object?


Solution

  • There is no way to store arrays in beans because RedBeanPHP cannot predict how you want the array to be represented in the database.

    The solution depends on what you want to do with this information later. Do you want to add other things than just weekdays, like evenings or overtime (in case of scheduling?), in this case I would opt for the most flexible yet easy solution:

    //Flexible solution
    foreach($days as $day) 
    $user->sharedDay[] = R::findOne('day',' name = ? ',array($day));
    

    Because we use sharedDay instead of ownDay, the records will not be duplicated. This solution creates a neat link table day_user.

    Of course you need to store the week days in the database once:

     $days = array('monday',...);
     foreach($days as $dayname) {
        $d = R::dispense('day');
        $d->name = $dayname;
        R::store($d);
     }
    

    If you want to be able to quickly trace a user with a certain weekday profile you may want to encode the days:

    //Performance solution
    function days($days) {
        $weekdays = array('sunday','monday','tuesday',...);
        $field = '';
        foreach($weekdays as $day) {
                $field .= (in_array($day,$days)) ? '1' : '0';
        }
        return $field;
    }
    
    
    $user->days = bindec(days($days)); 
    

    In this case you can find every user that has 'monday' and 'saturday' by querying: days = 33. That's really fast.

    If you don't care about the data at all you might go with:

    //Quick and dirty solution
    $user->days = implode(',',$days);