【发布时间】:2018-05-02 17:20:39
【问题描述】:
我有类似下表的内容 (tablename = applications):
| id | applicants |
| ------------- | ------------- |
| uuid-123-abc | [{'first_name':'Dave'},{'first_name':'Steve'}] |
我需要能够为它建立关系,这样我就可以走了:
$application->applicants 和(在本例中)获取包含两个 Applicant 模型的集合。
我假设我在某处需要一个申请人模型类。但是我什至不确定是否可以这样做,因为没有applicant 表。
我只是在尝试:
public function applicants()
{
return Collection::make([$this->applicants]);
但这不是一种关系,我正试图让它与Neromerx JsonApi一起工作。
事实上,如果有一种方法可以为 JsonApi 模仿这种行为,我会很乐意使用该解决方案。
到目前为止,我的人际关系都非常简单。而且我希望能够以同样的方式获得申请人:
use Neomerx\JsonApi\Schema\SchemaProvider;
class ApplicationSchema extends SchemaProvider
{
protected $resourceType = 'applications';
public function getId($application) {
return $application->id;
}
public function getAttributes($application) {
return [
.....
];
}
public function getRelationships($application, $isPrimary, array $includeRelationships) {
return [
'applicants' => [self::DATA => $application->applicants];
];
}
}
可以使用其中一种方法来完成吗?
我没有使用 Laravel,我只是在 Slim 中使用 Eloquent(5.5 版)。
【问题讨论】:
-
这种“关系”应该具备哪些特点?您是否只想从 JSON 字符串中获取
Applicant实例的集合? -
这应该就是所有需要的了,是的。它应该在 Eloquent 模型的“关系”范围内可用。
-
最后一句到底是什么意思?
-
Eloquent 模型有一个“relations”属性,它将包含所有现有的(如果需要的话)相关数据。 Here be the docs
-
为什么在您的案例中使用
$relations属性很重要?