雄辩的是,模型有很多但没有直接关系

时间:2019-02-18 16:17:38

标签: php eloquent

我无法理解这一点!我正在使用属性,但这导致运行多个查询,而不是一个

我有很多位置,它们都有自己的社交媒体联系人数据集。我的社交媒体和联系人数据存储在它自己的表中,这些表还链接到包含有关数据类型信息的表。

因此,例如。

位置

id      name      full_name
1       'Test'    'Testing'

location_contact

id      content     type_id     location_id
1      '4532432'       3            1

contact_types

id      value      link
3    'telephone'  'tel:'

一个位置可能具有多个相同的联系人类型,因此我需要将所有联系人分组为联系人类型。所以我的预期数据将是:

[
    0 => [
        'id' => 1,
        'name' => 'Test',
        'full_name' => 'Testing',
        'contact' => [
            'telephone' => [
                'id' => 3,
                'value' => 'telephone',
                'link' => 'tel:',
                'data' => [
                    0 => [
                        'id' => 1,
                        'content' => 4532432,
                        'type_id' => 3,
                        'location_id' => 1
                    ]
                ]
            ]
        ]
    ]
]

我将如何去做?还是仅通过一次查询就可以检索到更容易处理的数据?

1 个答案:

答案 0 :(得分:0)

我建议检查一下您的人际关系设计。一样,我建议您在位置模型上使用关系和变异器。

在“位置”模型上:

protected $appends = ['contact'];

public function getContactAttribute(){
    $res = [];
    $res['telephone'] = $this->contactTypes[0];
    $res['telephone']['data'] = $this->contacts;

    return $res;
}

public function contactTypes()
{
    return $this->belongsToMany("App\ContactType", 'location_contact', 'location_id', 'type_id');
}

public function contact()
{
    return $this->hasMany("App\ContactType", 'location_id');
}