我需要使模型与客户建立深厚的关系,但它会返回
SQLSTATE [42000]:语法错误或访问冲突:1055表达式#5 SELECT列表的内容不在GROUP BY子句中,并且包含未聚合的 列“ gis-web.areas.id”在功能上不依赖 GROUP BY子句中的列;这与 sql_mode = only_full_group_by(SQL:选择
zone_regions
。,areas
。,segments
。*来自zone_regions
内部联接areas
areas
。zone_id
=zone_regions
。id
内部联接hthree_regions
hthree_regions
。area_id
=areas
。id
内部联接segments
segments
。hthree_id
=hthree_regions
。id
分组依据zone_regions
。id
)
$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();
zone_regions
有areas
areas
有hthree_regions
hthree_regions
有segments
我需要获得zone_regions
下方所有内容的计数,例如:
zone_regions 1
具有20 areas
,2000 hthree_regions
和16000 segments
所以我可以计算与此zone region
相关的所有行,这就是我要达到的目的。
有什么想法吗?
答案 0 :(得分:0)
这是因为Laravel上的“严格模式”没有关闭。
解决方案:
yourproject/config/database.php
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方法)
希望它也可以帮助其他人。