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

时间:2017-10-22 22:43:23

标签: php mysql database laravel eloquent

我有以下表格:

Locations:
id
name

areas:
id
name

buildings:
id
name

Reports:
id
content
FK | building_id

如何在App \ Report Model文件中编写一种关系方法,允许我显示报告(位置)< - 来自\ App \ Location Model。

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

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

但是它返回了一个错误:

ErrorException(E_ERROR) 调用未定义的方法App \ Location :: whereHas()(查看:

1 个答案:

答案 0 :(得分:1)

您的位置模型应该扩展Eloquent

use Illuminate\Database\Eloquent\Model;

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(App\Building::class);
    }
}

class Building extends Model
{
    public function area()
    {
        return $this->belongsTo(App\Area::class);
    }
}

class Area extends Model
{
    public function location()
    {
        return $this->belongsTo(App\Location::class);
    }
}