为简化起见,假设我有3个表格:
类型:id,名称 单位:身份证,姓名,顺序,访问 unit_types:id,typeid,unitid
类型模型:
public function unitTypes()
{
return $this->hasMany('App\Unit_type' , 'typeid');
}
单元型号:
public function unitTypes()
{
return $this->hasMany('App\Unit_type' , 'unitid');
}
unit_types模型:
public function unit()
{
return $this->belongsTo('App\Unit');
}
public function type()
{
return $this->belongsTo('App\Type');
}
我想要实现的是当我获得特定类型ID时,我想获得与此类型相关联的单位并对其进行排序。我试过这个但没有运气:
$units=Unit_type::where('typeid' , '=' ,$id)->unit()->orderBy('visit')->take(10)->get();
但作为回报我得到这个错误:
调用未定义的方法Illuminate \ Database \ Query \ Builder :: unit()
在这种情况下,Laravel文档还不够清晰。所以我想知道如何在Eloquent中进行这种查询。
即使只有一个匹配该id的记录,以下调用实际上也会返回一个集合:
Unit_type::where('typeid' , '=' ,$id);
所以你要做的就是获得第一个,并在上面调用unit()
:
$units=Unit_type::where('typeid' , '=' ,$id)->first()->unit()->orderBy('visit')->take(10)->get();
要获取具有特定类型ID的所有单元,请考虑在单元模型上设置范围:
public function scopeOfTypeId($query, $type_id)
{
return $query->whereHas('unitTypes', function ($where_has_query) use ($type_id) {
$where_has_query->where('typeid', $type_id);
});
}
然后你可以这样打个电话来获得所有单位:
$units = Unit::ofTypeId($type_id)->get();
注意:我猜测模型和列的名称,因此您可能需要更改其中的一些。