gpt4 book ai didi

php - 组相关产品属性

转载 作者:行者123 更新时间:2023-11-30 01:34:23 26 4
gpt4 key购买 nike

我有一个产品表:

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 等中使用这些数据变得更加容易。

最佳答案

您可能还没有意识到,但是使用 Eloquent,您已经拥有了一切。一旦您在模型中创建了关系,您只需要一个根模型即可到达与其相关的每个模型。

假设您有产品型号:

<?php

class Product extends Eloquent {

}

以及您的产品详细信息模型:

<?php

class ProductDetail extends Eloquent {

}

这样你就可以在它们之间建立关系

class Product extends Eloquent {

public function details()
{
return $this->hasMany('ProductDetail');
}

}

现在,如果您的 Controller 将模型列表传递给您的 UI:

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>

关于php - 组相关产品属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com