Search code examples
redbean

RedBean (ORM) Get Bean with his relations like other Bean


I'm storing a product Bean, by this way:

$product = R::dispense( 'product' ); 
$product->name = $_POST['name']; 
$product->description = $_POST['description']; 
$product->price = $_POST['price']; 
$product->category = $_POST['category']; 
R::store( $product ); 

How can I indicate that the category's attribute is an id reference (or FK) to the category Bean? I want get the category Bean like this way:

$products = R::find( 'product' ); 
foreach( $products as $product ) 
   $productCategory = $product->category->name;

Solution

  • The way I would do it is this IF you don't have the database table already configured:

    $product = R::dispense( 'product' ); 
    $product->name = $_POST['name']; 
    $product->description = $_POST['description']; 
    $product->price = $_POST['price']; 
    $product->category = R::load('category',$_POST['category']); 
    R::store( $product );
    

    BUT I believe if your database has a foreign index assigned for category and it points to the category table, then you can do what you did above. So on your product table, have a column category_id and make it a foreign index to category.id and it should work. I can test it later and give you a more definitive answer, but this is just going off of what I know offhand.