我有一个产品表:
products
-id
-name
-image
还有product_atts表:
product_attributes
-product_id (FK)
-size (1, 2)
-memebership (1, 2, 3, 4, 6, 11)
-price
现在,在查询product_attributes
表并加入products
表时,我得到了所有变体:
Array
(
[0] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 1
[price] => 0.00
)
[1] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 2
[price] => 0.00
)
[2] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 3
[price] => 0.00
)
[3] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 4
[price] => 0.00
)
[4] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 6
[price] => 0.00
)
[5] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 1
[membership] => 11
[price] => 0.00
)
[6] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 1
[price] => 0.00
)
[7] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 2
[price] => 0.00
)
[8] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 3
[price] => 0.00
)
[9] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 4
[price] => 0.00
)
[10] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 6
[price] => 0.00
)
[11] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => 2
[membership] => 11
[price] => 0.00
)
)
有没有办法让我得到一个如下所示的结果:
Array
(
[0] => stdClass Object
(
[name] => Product 1
[image] => Product1.png
[size] => stdClass Object
(
[0] => 1,
[1] => 2
)
[membership] => stdClass Object
(
[0] => 1,
[1] => 2,
[2] => 3,
[3] => 4,
[4] => 6,
[5] => 11
)
[price] => 0.00
)
)
这使得在我的UI等中使用这些数据变得更加容易。
答案 0 :(得分:0)
你可能还没有意识到它,但是使用Eloquent,你已经拥有了这一切。只要您在模型中创建关系,就需要一个根模型来覆盖与之相关的每个模型。
假设您有产品型号:
<?php
class Product extends Eloquent {
}
和您的产品详细信息型号:
<?php
class ProductDetail extends Eloquent {
}
所以你可以建立他们之间的关系
class Product extends Eloquent {
public function details()
{
return $this->hasMany('ProductDetail');
}
}
现在,如果你的控制器将一个模型列表传递给你的用户界面:
public function index()
{
return View::make('site.products')->with('products', Product::all());
}
在您的界面中,您将能够:
<ul>
@foreach($products as $product)
<li>
<p>Product: $product->name</p>
<p>Sizes:</p>
<ul>
@foreach($product->details as $detail)
<li>
{{$detail->size}}
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>