Search code examples
phpmysqlredbean

query over many to many relationship in redbeanphp


i have two tables which are "user" and "estate" and i make a many-many relation between those table with this code :

$user->link("estatetrans", (array("trtype" => $trtype, "indate" => time())))->estate = $estate;

"estatetrans" is name of table that contain relation between these two table :

now i want query over "estatetrans" table by filtering on trtype column.

i do this action using this code :

$trans = R::findAll("estatetrans", "users_id=:uid and trtype=:trt" , array("uid"=>$userId , "trt"=>$trtype)) ; 
    $estates = array() ; 
    foreach ($trans as $tr)
    {
        array_push($estates, $tr->estate) ; 
    }

but i know it is not a perfect and good principal. how can i do this work by redbeanphp methods?


Solution

  • The RedBeanPHP way would be to use the sharedList instead of findAll, for example, something like this:

    list($e, $t) = R::dispenseAll('estate,transaction');
    $e
      ->link('estate_transaction',['type'=>'auction'])
      ->transaction = $t;
    R::store($e);
    $e = R::findOne('estate');
    $x = $e
         ->withCondition(' estate_transaction.type = ? ',['auction'])
         ->sharedTransaction;
    

    $x now contains the transactions, filtered by the estate_transaction.type column.

    Note that you can also rename the link table if you want an even fancier solution.

    cheers Gabor