【问题标题】:OctoberCms. How to add attribute to Model?十月Cms。如何为模型添加属性?
【发布时间】: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-&gt;id

标签: php laravel octobercms


【解决方案1】:

我假设您有 2 个模型 Service(parent) 和 Sale(it's child)

我还从template for loop 假设,它是hasMany 关系(其中service 有很多sale 的记录)

Salecategory_id 是父级的id

所以在父模型中你可以定义关系

class Service extends Model
{
    public $hasMany = [
        'sales' => ['Acme\Blog\Models\Sale', 'key' => 'category_id']
        // here you need to add proper namespace for your model
    ];
}

现在当您需要获取Sale 的相关记录时,您可以调用此关系别名sales

我们假设我们从组件传递servicesList

public function onRun()
{
    $this->page['servicesList'] = Service::all();
}

现在您可以在页面内写这样的内容,因为servicesList 将可用于页面(其模型集合Service

{% for service in servicesList %}    
   <h1>{{service.name}}</h1>
   <ul class="children_list">
     {% for children in service.sales %} 
       <!-- its relation name 'service.sales' which we defined in model -->
       <li>{{children.name}}</li>
     {% endfor %}
   <ul>    
{% endfor %}

如果您还有任何疑问,请在 cmets 中告诉我。

【讨论】:

    【解决方案2】:

    为您的模型添加适当的关系

     public function children()
    {
        return $this->hasMany(Sale::class,'category_id','id');
    }
    

    然后你让孩子做你想做的事

    $model = Model::with('children')->find('id');
    
    @foreach($model->children as $child)
    
    @endforeach
    

    【讨论】:

    • 虽然这会将 OP 指向正确的方向,但在 OctoberCMS 中声明关系的方式与在 Laravel 中不同。
    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2017-05-02
    • 2018-12-06
    相关资源
    最近更新 更多