Octobercms Child Relationship Of Relationships

- 1 answer

Im working in a octobercms plugin and i have the following models in it:

  • Houses
  • Pays
  • Owners

In Houses model i have the following relationship:

public $hasManyThrough = [
      'owner' => [
        'table' => 'author_plugin_houses_owners',
        'key' => 'houses_id',
        'otherKey' => 'owners_id'

this relationship has a intermediate table 'author_plugin_houses_owners':

| hoses_id   |  owners_id  | active |

And in Pays model i have the following relationship:

public $belongsTo = [
        'houses' => ['Author\Plugin\Models\Houses']

this model corresponds to a table like this:

| id | hoses_id | amounth | payed | debt |

in the table i have a column "houses_id", the question is, how i can access to "owner" relationship declared in "Houses" model since "Pays" model? i need access to it because i need printed "owner_name" on list view in the plugin backend.

owner table:

| id | owner_name | active |

thanks a lot!



I assume that Pay belongs to only one house.

public $belongsTo = [        
    'house' => ['Author\Plugin\Models\Houses'] 
  // ^ you can use house instead houses for relation name

Now we can access owner with relation chain


Since you made relation hasMany one house can have multiple owners [ hasManyThrough ]

so this will return you a list of owners.

As in list view you need to use it, You can define partial type column

        label: id
        type: number
        searchable: true
        sortable: true

    .... other fields ...

        label: Owner
        type: partial
        path: $/hardiksatasiya/demotest/models/sort/_ownername_column.htm

Make sure to replace the path with your own plugin author name and path.

Now inside partial, you can write your actual logic [ this must be in PHP not in twig ]

// this is hasmany relation so we expect multiple owners
$owners = $record->house->owner;
$ownerArr = [];
foreach($owners as $ownr) {
    $ownerArr[] = $ownr->owner_name;
$output = implode($ownerArr, ', ');

<?php echo $output ?>

If there is only one owner it will show Hardik one name only if there are multiple owners it will show Hardik, Noe comma separated values.

enter image description here

if any doubts please comment.