【发布时间】:2018-01-08 05:14:58
【问题描述】:
我需要按父模型 ID 显示列表子模型: 如果我在模型中使用它就可以了:
public function getIdAttribute($id)
{
$sales = Sale::where('category_id',$id)->get();
foreach ($sales as $sale) {
$clean_fields[$sale->attributes['id']]['name'] = $sale->attributes['name'];
$clean_fields[$sale->attributes['id']]['price'] = $sale->attributes['price'];
}
return $clean_fields;
}
在模板中显示列表:
{% for service in servicesList %}
<h1>{{service.name}}</h1>
<ul class="children_list">
{% for children in service.id %}
<li>{{children.name}}</li>
{% endfor %}
<ul>
{% endfor %}
我将属性 id 修改为数组。它在模板中工作,但在后端我有错误,因为 id 没有传递给列表控制器。如何在组件模板中获取子模型?
【问题讨论】:
-
id属性很可能是您模型的主键,因此您不应覆盖 getter,除非您要提供另一种方法来识别模型。 -
@fubar,我明白了。有哪些替代方案?
-
我建议您将
getIdAttribute函数命名为不同的名称,这样您就不会覆盖id属性获取器。从函数的外观来看,它似乎与获取id没有任何关系,因此当前名称似乎不是很直观或合适。 -
@fubar,那我如何获取当前的模型id?
-
您可以使用
id属性访问它 -$model->id
标签: php laravel octobercms