ormredbean

Redbean: How does one get last inserted id of owned Bean?


I use RedBeanPHP 3.5.1 for ORM in my MVP project (powered by Nette FW).

I need to get ID of the last inserted element, that is owned by element from another table. Below you can find method representing functionality which I just described:

public function createSite($userId, $siteName, $feedUrl, $reloadTime, $reloadRate){
    $site = R::dispense('site');
    $site->user_id = $userId;
    $site->name = $siteName;
    $site->feed = $feedUrl;
    $site->reload_time = $reloadTime;
    $site->reload_rate = $reloadRate;

    $user = R::load('user', $userId);
    $user->ownSite[] = $site;
    $id = R::store($user);

    return $id; 
}

Now I would assume that line

$id = R::store($user);

would store site ID into $id variable since it is owned by already existing user. Instead of that it fills variable with user ID that I have no further use for.

So my question is: How do I get last inserted ID of owned bean that was just created by calling R::store() method on parent (just loaded) bean? Is there an implementation on this in RedBean or do I have to do this manually?

I browsed every corner of RedBeanPHP project web but so far no luck.

Thanks for possible suggestions, guys.


Solution

  • Using common sense I finally figured out how to solve this elegantly and since no one answered my question so far let my just do that myself.

    Since R::store($user) is capable of storing both $user and $site, there is misleadingly no need to store $site object manually.

    But if you need to get last inserted id of owned bean, there is really no harm in doing so. By storing $site object framework will do the exact same thing and on top of that it returns resired id.

    So the correct method implementation looks like this:

    public function createSite($userId, $siteName, $feedUrl, $reloadTime, $reloadRate){
        $site = R::dispense('site');
        $site->user_id = $userId;
        $site->name = $siteName;
        $site->feed = $feedUrl;
        $site->reload_time = $reloadTime;
        $site->reload_rate = $reloadRate;
    
        $user = R::load('user', $userId);
        $user->ownSite[] = $site;
    
        $id = R::store($site);
        R::store($user);
    
        return $id;
    }
    

    So in conclusion, hats off to RedBeanPHP ORM FW and I sincerely hope this helps people with similar problem in the future.