我正在使用 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 showHardik, Noe
comma separated values.
如有疑问请评论。
关于php - Octobercms子关系的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732576/