Laravel深层关系查询

时间:2020-04-14 06:58:45

标签: php mysql laravel

我需要使模型与客户建立深厚的关系,但它会返回

SQLSTATE [42000]:语法错误或访问冲突:1055表达式#5 SELECT列表的内容不在GROUP BY子句中,并且包含未聚合的 列“ gis-web.areas.id”在功能上不依赖 GROUP BY子句中的列;这与 sql_mode = only_full_group_by(SQL:选择zone_regionsareassegments。*来自zone_regions内部联接areas areaszone_id = zone_regionsid内部联接hthree_regions hthree_regionsarea_id = areasid内部联接segments segmentshthree_id = hthree_regionsid分组依据 zone_regionsid

代码

$data = DB::table('zone_regions')
        ->join('areas', 'areas.zone_id', '=', 'zone_regions.id')
        ->join('hthree_regions', 'hthree_regions.area_id', '=', 'areas.id')
        ->join('segments', 'segments.hthree_id', '=', 'hthree_regions.id')
        ->select(
            'zone_regions.*',
            'areas.*',
            'segments.*'
        )
        ->groupBy('zone_regions.id')
        ->get();

逻辑

  1. zone_regionsareas
  2. areashthree_regions
  3. hthree_regionssegments
  4. 以此类推,以后我将添加...

我想从这些数据中得到什么?

我需要获得zone_regions下方所有内容的计数,例如:

zone_regions 1具有20 areas2000 hthree_regions16000 segments

所以我可以计算与此zone region相关的所有行,这就是我要达到的目的。

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

这是因为Laravel上的“严格模式”没有关闭。

解决方案:

  1. 打开yourproject/config/database.php
  2. 找到strict => true(将其更改为false)

别忘了运行php artisan config:cache

答案 1 :(得分:0)

根据您的错误,问题出在您的数据库上,它表明您已启用

sql_mode=only_full_group_by

要通过禁用此模式

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

有关更多信息,您可以查看此文档https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

尽管如此,我可以看到您的查询没有得到您想要的,您需要诸如count之类的聚合函数。

data = DB::table('zone_regions') ->join('areas', 'areas.zone_id', '=', 'zone_regions.id') ->join('hthree_regions', 'hthree_regions.area_id', '=', 'areas.id') ->join('segments', 'segments.hthree_id', '=', 'hthree_regions.id') ->select( 'zone_regions.id' , DB::raw(' SUM(case when areas.id IS NOT NULL then 1 else 0 end) as areas,  SUM(case when hthree_regions.id.id IS NOT NULL then 1 else 0 end) as hthree_regions), SUM(case when segments.id IS NOT NULL then 1 else 0 end) as segments')->groupBy('zone_regions.id') ->get();

希望对您有帮助

答案 2 :(得分:0)

已解决

在使用查询方法进行大量工作的过程中,我决定使用模型绑定功能hasManyThrough source

我已经在模型中定义了3个新函数,并在我的变量(带有)中调用了它们,现在我有了所需的数据。

代码

Model

class ZoneRegion extends Model
{
    protected $fillable = [
        'name',
    ];

    public function areas(){
        return $this->hasMany(Area::class, 'zone_id', 'id');
    }

    public function segments()
    {
        return $this->hasManyThrough(Segment::class, HthreeRegion::class, 'area_id', 'hthree_id');
    }

    public function links()
    {
        return $this->hasManyThrough(Link::class, Segment::class, 'hthree_id', 'segment_id');
    }

    public function cabels()
    {
        return $this->hasManyThrough(CableType::class, Link::class, 'cable_id', 'id');
    }
}

Controller

$zones = ZoneRegion::orderby('id', 'desc')->with(['areas', 'segments', 'links', 'cabels'])->get();

这很成功,现在我要做的就是获取length的数据(JS方法)或count()的数据(Blade方法)

希望它也可以帮助其他人。