1

这似乎是一个简单的问题,但我莫名其妙地感到困惑。

如果我用以下方法创建几个 bean:

list($product1, $product2, $product3) = R::dispense('product', 3);
...

和几个类别:

list($cat1, $cat2) = R::dispense('category', 2);
...

然后将它们与:

$product1->sharedCategory[] = $cat1;
$product3->sharedCategory[] = $cat1;

然后如何查询与 $cat1 相关的所有产品?我应该取回产品 1 和 3。

就像我说的,简单。在 mysql 中,这很容易,所以总是可以只向 red bean 发送一个 sql 字符串,但肯定有办法做到这一点。

谢谢。

4

1 回答 1

4

我认为它反过来(对不起,如果我错了),因为从逻辑上讲,一个类别有很多产品,而不是你定义的一个产品很多类别。

========编辑部分=====================

我删除了这里发布的一个小资源,因为手册Manuall 非常简单,更好,并且对于如何连接、建立关联、更新等的示例代码非常有帮助。我相信你会从中受益匪浅。如果手册有任何困难,很乐意提供帮助。

========== 附加信息 ========================

这里我只是放了一些源代码,并没有改变我的答案。试试这个代码,它可以按照你的意愿工作!

<?PHP
echo '<pre>';

require('rb.php'); 
$toolbox = R::setup('mysql:host=localhost;dbname=my_ORM','root','');
$farm = R::dispense('building');

//create the product list
list($product1,$product2,$product3) = R::dispense('product',3);
//add attributes 
$product1->name='prod1';
$product2->name='prod2';
$product3->name='prod3';


//create a list of categories 
list($category1,$category2) = R::dispense('category',2);
//add attributes 
$category1->name='categ1';
$category2->name='categ2';

//the connect beans together
R::associate($category1,$product1);
R::associate($category1,$product2);
R::associate($category1,$product3);
R::associate($category2,$product3);

//then store
R::store($product1);
R::store($product2);
R::store($product3);
R::store($category1);
R::store($category2); 

//get id for category 1
$categId=R::getCell( " select  `id` from `category` where `name`='categ1'  ");
//get products for category 1
$results = 
R::getAll( "
SELECT  `product`.`id`,`product`.`name` 
FROM `product`  left JOIN `category_product`
on `category_product`.`product_id`= `product`.`id` 
where  `category_id`='".$categId."' ");
//display
print_r($results);

//get categories for product3
$prodId=R::getCell( " select  `id` from `product` where `name`='prod3'  ");
$results = 
R::getAll( "
SELECT  `category`.`id`,`category`.`name` 
FROM `category`  left JOIN `category_product`
on `category_product`.`category_id`= `category`.`id` 
where  `product_id`='".$prodId."' ");
print_r($results);

?>
于 2011-10-03T21:46:05.947 回答