首页 > 解决方案 > 我已经在模型中定义了关系,但是如何以 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
  }
]

标签: sqllaraveleloquent

解决方案


你不需要这个特定查询的关系,你可以像这样使用 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');

我希望它有帮助


推荐阅读