sql - 我已经在模型中定义了关系,但是如何以 Eloquent 的方式编写复杂的查询
问题描述
我在现有应用程序中有一个查询现在我需要以雄辩的方式更新查询我有以下关系结构我如何以雄辩的方式编写以下查询
我想以雄辩的方式更改的控制器查询
foreach ($data['Divisions'] as $sections) {
$SecQry1 = "SELECT sections.id, sections.division_id, sections.code, sections.name ,specifications.description
from specifications inner JOIN sections on specifications.section_id=sections.id where specifications.status='active'
AND specifications.manufacturer_id = $user->id AND sections.division_id=" . $sections->id . " group by sections.id";
$SectionsDivision1 = DB::select($SecQry1);
foreach ($SectionsDivision1 as $key => $selectionDiv) {
array_push($selectionDiv_array1, $selectionDiv);
}
}
class Specification extends Model {
protected $table = 'specifications';
public function section()
{
return $this->belongsTo('App\Section');
}
}
类部分扩展模型{
protected $table = 'sections';
public function specifications()
{
return $this->hasMany('App\Specification', 'section_id');
}
public function division()
{
return $this->belongsTo('App\Division');
}
}
class Division extends Model {
protected $table = 'divisions';
protected $fillable = array('name', 'description', 'code','status');
public function sections()
{
return $this->hasMany('App\Section', 'division_id');
}
}
0 => {#1063 ▼
+"id": 1
+"division_id": 1
+"code": "03 01 00"
+"name": "Maintenance of Concrete"
+"description": null
}
]
解决方案
你不需要这个特定查询的关系,你可以像这样使用 Laravel Eloquent join
:
$SectionsDivision1 = Specification::join('sections', 'specifications.section_id', '=', 'sections.id')
->where([
'specifications.status' => 'active',
'specifications.manufacturer_id' => $user->id,
'sections.division_id' => $sections->id
])->select('sections.id', 'sections.division_id', 'sections.code', 'sections.name', 'specifications.description')
->groupBy('sections.id');
我希望它有帮助
推荐阅读
- r - 如何在 ggplot2 中绘制 2 个样本的 QQ 图?
- sql-server - 遍历 SQL Server 中的逗号分隔值
- json - Axios 解析打字稿对象不正确
- python - 按日期时间屏蔽数据帧时,“模块”对象不可调用
- c++ - 我在多边形函数中的观点有什么问题?
- sql - 数据长度v/s数据精度
- javascript - 从 "onkeypress" 转换为 "addeventlistener("keypress",()=>{})
- php - Laravel 7 创建多对多迁移时出错
- javascript - 第 4 行的类型错误:回调不是函数 JavaScript 回调
- c# - 影响 Azure 应用服务 (ASP.NET WebApi) 中的并发性的限制因素是什么?