0

我有两个名为contactsand的表clients。两个表都有group_id作为外键。现在,当用户从表中找到一个组时,我想phone从两个表中获取列值。我正在尝试这样的事情。但是得到空数组。有人能帮帮我吗!$request->groupidgroups

$getPhoneNumbers = Group::with(['hasContacts' => function($query){
                             $query->select('phone')->where('is_active', 1);
                        }])->with(['clients' => function($q){
                             $q->select('phone')->where('status', 1);
                        }])->where('id', $request->groupid)->get();

模型中 -

public function clients()
{
    return $this->hasMany('App\Client', 'group_id', 'id');
}

public function hasContacts()
{
    return $this->hasMany('App\Contact', 'group_id', 'id');
}
4

2 回答 2

1

您还需要选择group_idLaravel 所需的外键,以将预先加载的结果与其父级匹配:

$getPhoneNumbers = Group::with(['hasContacts' => function($query){
                             $query->select('group_id', 'phone')->where('is_active', 1);
                        }])->with(['clients' => function($q){
                             $q->select('group_id', 'phone')->where('status', 1);
                        }])->where('id', $request->groupid)->get();
于 2019-06-30T14:28:00.477 回答
0

如果你想使用关系方法,你应该首先获取组对象,然后调用它们。另外,请重命名hasContacts()contacts()以遵循约定。

$group = Group::find($request->groupid);

if (!$group) {
    # group not found
}

$clientPhoneNumbers = $group->clients()->where('status', 1)->pluck('phone')
$contactPhoneNumbers = $group->contacts()->where('is_active', 1)->pluck('phone')

这使用 pluck 将单个列作为 eloquent Collection。您可以使用$clientPhoneNumbers->toArray()以数组形式获取电话号码(对于 other 也是如此Collection)。

团体型号:

public function clients()
{
    return $this->hasMany('App\Client', 'group_id', 'id');
}

public function contacts()
{
    return $this->hasMany('App\Contact', 'group_id', 'id');
}
于 2019-06-30T12:16:20.183 回答