Laravel:如何制作列名的键?

Laravel:如何制作列名的键?

问题描述:

I'm bending my mind for some time now over this problem. Could someone please help me?

I have two tables: products and product_attributes. The product has all basic product information and product_attributes has all specific information for products on different categories. It's much like the magenta attribute system. this table has 4 columns: id, product_id, attribute_name, attribute_value.

Now let's say a product has 2 attributes:

------------------------------------------------------
| id | product_id | attribute_name | attribute_value |
------------------------------------------------------
| 1  | 123        | length         | 123cm           |
------------------------------------------------------
| 2  | 123        | material       | Denim           |
------------------------------------------------------
| 3  | 123        | season         | Summer          |
------------------------------------------------------

Now if I set up the eloquent relationships and query a product, I get a product object with all three attributes. So far this is what I wanted. But now in a blade template I would like to be able to do something like this:

$product->attribute->length

Is this even possible or do I need to achieve these kind of things with a total different approach (like creating different tables for different product types/categories)?

Thanks in advance!

我现在已经在这个问题上弯曲了一段时间。 有人可以帮助我吗? p>

我有两个表:products和product_attributes。 该产品包含所有基本产品信息,product_attributes包含不同类别产品的所有特定信息。 它很像洋红色属性系统。 此表有4列:id,product_id,attribute_name,attribute_value。 p>

现在假设产品有2个属性: p>

   -  --------------------------------------------------  -  \ N |  id |  product_id |  attribute_name |  attribute_value | 
 ----------------------------------------------  -------- 
 |  1 |  123 | 长度|  123cm | 
 ----------------------------------------------  -------- 
 |  2 |  123 | 材料| 牛仔布| 
 ----------------------------------------------  -------- 
 |  3 |  123 | 季节| 夏天| 
 ----------------------------------------------  -------- 
  code>  pre> 
 
 

现在,如果我设置了雄辩的关系并查询产品,我会得到一个包含所有三个属性的产品对象。 到目前为止,这是我想要的。 但现在在刀片模板中,我希望能够做到这样的事情: p>

  $ product-> attribute-> length 
  code>   pre> 
 
 

这是否可行,或者我是否需要采用完全不同的方法来实现这些目标(例如为不同的产品类型/类别创建不同的表)? p> 提前致谢! p> div>

length is a tuple value not an attribute you need

$product->attribute->where('attribute_name', 'length')

or

$product->attribute->whereAttributeName('length')