php - Octobercms子关系的关系

标签 php laravel octobercms

我正在使用 octobercms 插件,其中有以下模型:

  • 房屋
  • 付费
  • 所有者

在 Houses 模型中,我有以下关系:

public $hasManyThrough = [
      'owner' => [
        'Author\Plugin\Models\Owner',
        'table' => 'author_plugin_houses_owners',
        'key' => 'houses_id',
        'otherKey' => 'owners_id'
      ]
    ];

此关系有一个中间表“author_plugin_houses_owners”:

+------------+-------------+--------+
| hoses_id   |  owners_id  | active |
+------------+-------------+--------+

在支付模型中我有以下关系:

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

这个模型对应的表格如下:

+----+----------+---------+-------+------+
| id | hoses_id | amounth | payed | debt |
+----+----------+---------+-------+------+

在表中我有一列“houses_id”,问题是,我如何访问自“Pays”模型以来在“Houses”模型中声明的“所有者”关系?我需要访问它,因为我需要在插件后端的 ListView 上打印“owner_name”。

所有者表:

+----+------------+--------+
| id | owner_name | active |
+----+------------+--------+

非常感谢!

最佳答案

我假设Pay只属于一所房子。

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

现在我们可以通过关系链访问所有者

$payModel->house->owner 

自从您建立了关系hasMany以来,一所房子可以有多个所有者 [hasManyThrough]

因此这将返回一个所有者列表。

如在 ListView 中需要使用它,您可以定义partial类型列

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

    .... other fields ...

    owner_name:
        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.

现在在partial中,您可以编写实际逻辑[这必须在PHP中而不是在twig中]

<?php
// 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

如有疑问请评论。

关于php - Octobercms子关系的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732576/

相关文章:

php - 这个数据库调用有什么问题?

php - Laravel 5 覆盖路由资源参数

php - laravel 方法 "inRandomOrder()"真的是随机的吗?

seo - 10月CMS博客分页内容重复问题

octobercms - 十月 CMS - 自定义字段

php - 从下拉列表中检索错误数据 MYSQL PHP

javascript - 如何从 &lt;scriptscript type ="application/ld+json"> 获取内容 json

php artisan key :generate doesn't do anything

sorting - 十月 CMS - 排序记录 - 工具栏图标部分示例?

php - 使用 laravel,如何在 3x3 GridView 中显示名为 'products' 的 HTML 类,同时连接到数据库以获取产品