创建模型方法以从另一个模型获取数据



我有下表:

Locations:
id
name
areas:
id
name
buildings:
id
name
Reports:
id
content
FK | building_id
如何在应用程序\报表模型

文件中编写关系方法,使我能够从\应用\位置模型<显示报表(位置)。>

我在报告模型中尝试过这个:

public function location()
    {
        return Location::whereHas('areas', function($q){
            $q->whereHas('observations',function ($q){
                $q->where('observations.id',$this->id);
            });
        })->get();
    }

但它返回了一个错误:

错误异常 (E_ERROR)调用未定义的方法 App\Location::whereHas() (查看:

您的位置模型应扩展 雄辩

use IlluminateDatabaseEloquentModel;
class Location extends Model
{
    ...

此外,最好为此使用Laravel关系。你最终会得到这样的代码

public function location()
{
    return $this->building->area->location;
}

您将需要这样的东西

class Report extends Model
{
    public function location()
    {
        return $this->building->area->location;
    }
    public function building()
    {
        return $this->belongsTo(AppBuilding::class);
    }
}
class Building extends Model
{
    public function area()
    {
        return $this->belongsTo(AppArea::class);
    }
}
class Area extends Model
{
    public function location()
    {
        return $this->belongsTo(AppLocation::class);
    }
}

最新更新