This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

clone458396
clone458396

Hello,

I have two tables: regions and places. There's a one-to-many relationship between regions and places. In other words, there are multiple places in a region.

My tables look roughly like this:

regions
=======
id
name

places
=====
id
region_id
name

On the front end, my intention is to do something like this (in the page):

title = "Region and Places"
url = "/region/:slug"
layout = "default"
is_hidden = "0"

[region]
slug = "{{ :slug }}"
==
<h1>{{ region.name }}</h1>
{% for place in region.places %}
    <li>
            <h3>{{ place.name }}</h3>
    </li>
{% else %}
    <li class="no-data">No places</li>
{% endfor %}

My attempt (which failed) was to add the following code to my region component:

public function onRun()
{
    $this->region = $this->page['region'] = $this->loadRegion();
}
protected function loadRegion()
{
    $slug = $this->property('slug');
    $region = RegionsModel::with('places')->where('slug', $slug)->first();
    return $region;
}

.. and this almost worked, but only the first place name was output. Can anyone help me, or point me to an existing free plug-in that does something similar?

Thanks! Bret

Last updated

Wouter
Wouter

Try

$slug = $this->property('slug');
    $region = RegionsModel::with('places')->where('slug', $slug)->get();
Cpt.Meatball
Cpt.Meatball

Have you defined places in you Region Model? If so? Use the alias you used in the hasMany variable to call your relationship in the view.

$hasMany = [
'places' => ['user/plugin/model/name', etc...]

]

If you set this up correctly you can access you relationship without pre-loading your relationship. Just like you are already doing :)

Last updated

1-3 of 3

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.