laravel - 使用 Laravel ORM 中的 where 条件从多个关系表中选择特定列值
问题描述
我有两个名为contacts
and的表clients
。两个表都有group_id
作为外键。现在,当用户从表中找到一个组时,我想phone
从两个表中获取列值。我正在尝试这样的事情。但是得到空数组。有人能帮帮我吗!$request->groupid
groups
$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');
}
解决方案
您还需要选择group_id
Laravel 所需的外键,以将预先加载的结果与其父级匹配:
$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();
推荐阅读
- python - 如何使用函数显示对象的属性值
- python - 如何在 Python 中创建一个密码来结束被拒绝的代码的以下部分?
- r - 无法安装 RCall - Julia 包
- amazon-dynamodb - IN 语句 DynamoDB 以获取选项可能为 4 的记录
- python - Python UnboundLocalError:从字典中选择单词的函数出现问题
- java - 将传统消息产生/队列转换为反应器中的通量
- python - 使用 Python 中字符串列表中的名称进行动态子类化
- maven - Maven(与第谷)在物化产品时失败
- html - 单击 div 时避免 :focus 样式(仅在 tab 键上)
- reactjs - React onPaste 窗口不会被调用,但可以在 Mac 上运行