How to exclude tables/children from result in RedBeanPHP

260 Views Asked by At

I have modelled a relation like this is RedBeanPHP:

Car
id    color    ownPart

Part
id    name

So RedBean creates the SQL tables as expected:

Car
id    color

Part
id    name    car_id

This works great.

However, I have other tables in my DB, e.g. a User that also has a car_id identifying the users car.

When I want to query all Cars and its children (Parts) by

$cars = R::find('car');
$foo = R::exportAll( $cars ); echo json_encode($foo);

the JSON also contains every User related to a car.

How can I query just the cars with their "real" children?

2

There are 2 best solutions below

2
On

exportAll specifies a third parameter $filter that you should be able to use to specify which relationships are also exported:

$foo = R::exportAll($cars, false, array('part'));
0
On

Please read Jacobs Answer (https://stackoverflow.com/a/27253767/2707529) if you have the problem at just on level (see my comment below his answer).

I had multidimensional arrays to filter, so after hours of trying I finally got at least a workaround by not filtering what I want but deleting what I do not want:

$cars = R::find('car');
$foo = R::exportAll( $cars );

$keystoremove = array("ownPart", "ownBrokenpart");
delFromArray($foo, $keystoremove );

echo json_encode($foo);


function delFromArray(&$array, $keys) { 
  foreach ($array as $key => &$value) { 
      if (in_array($key, $keys, true)){
        unset($array[$key]);
      }
      else {
        if (is_array($value)) { 
            delFromArray($value, $keys); 
        }
      }

  }
}