Ad

OctoberCms. How To Add Attribute To Model?

- 1 answer

I need display list child models by parrent model id: it's work if i use this in model:

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;
}

Display list in template:

{% for service in servicesList %}

   <h1>{{service.name}}</h1>
   <ul class="children_list">
     {% for children in service.id %}
       <li>{{children.name}}</li>
     {% endfor %}
   <ul>

{% endfor %}

i modified attribute id into array. It's work in template, but in backend i have error, because id not passed to list controller. How i can get child models in component template?

Ad

Answer

I am assuming that you are having 2 models Service(parent) and Sale(it's child)

I am also assuming from template for loop that, it is hasMany relation (where service has many records of sale)

where Sale is having category_id which is id of parent.

so inside parent model you can define relation

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

now when you need to fetch relative records of Sale you can call this relation alias sales.

we assume that we are passing servicesList from component.

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

now inside page you can write something like this as servicesList will be available to page (its collection of model of 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 %}

if you have any further doubt please let me know in comments.

Ad
source: stackoverflow.com
Ad