首页 > 解决方案 > 使用 Laravel ORM 中的 where 条件从多个关系表中选择特定列值

问题描述

我有两个名为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');
}

标签: laravellaravel-5eloquenteloquent-relationship

解决方案


您还需要选择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();

推荐阅读