使用laravel属于关系时调用未定义函数


call to undefined function when using laravel belong to relation

为了简化,假设我有3个表:

类型:id, name
单位: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_type model:

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();

注意:我猜你的模型和列的名称,所以你可能需要改变其中的一些。