Laravel Eloquent 将非关系数据附加到结果中
Laravel Eloquent appending a non-relation ship data with the result
我有这个模型文件:-
namespace App;
use Illuminate\Database\Eloquent\Model;
class Observation extends Model
{
protected $fillable = ['observation', 'recommendation', 'priority', 'report_asset_id'];
protected $appends = ['facility'];
public function attachments()
{
return $this->hasMany('App\ObservationAttachment');
}
public function report_facility()
{
return $this->belongsTo('App\ReportFacility');
}
public function getFacilityAttribute()
{
return $this->report_facility()->facility;
}
}
这是我的查询代码:-
$observations = Observation::orderBy('created_at','desc')
->with('attachments')->get();
return response()->json($observations);
我正在尝试附加 getFacilityAttribute 以包含在结果数组中。
我尝试使用受保护的 $append 模型数组但出现错误:-
Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsTo::facility()
下面这行是不正确的:
return $this->report_facility()->facility
您正在开始一个查询,将 report_facility
作为函数调用 (report_facility()
),returns 一个查询生成器对象,facility
函数未知.
你应该做的:
return $this->report_facility->facility
在这种情况下,eloquent 将为您提供 ReportFacility 模型,您可以从中检索设施 属性 或关系。
类似于:
return $this->report_facility()->first()->facility
我有这个模型文件:-
namespace App;
use Illuminate\Database\Eloquent\Model;
class Observation extends Model
{
protected $fillable = ['observation', 'recommendation', 'priority', 'report_asset_id'];
protected $appends = ['facility'];
public function attachments()
{
return $this->hasMany('App\ObservationAttachment');
}
public function report_facility()
{
return $this->belongsTo('App\ReportFacility');
}
public function getFacilityAttribute()
{
return $this->report_facility()->facility;
}
}
这是我的查询代码:-
$observations = Observation::orderBy('created_at','desc')
->with('attachments')->get();
return response()->json($observations);
我正在尝试附加 getFacilityAttribute 以包含在结果数组中。
我尝试使用受保护的 $append 模型数组但出现错误:-
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::facility()
下面这行是不正确的:
return $this->report_facility()->facility
您正在开始一个查询,将 report_facility
作为函数调用 (report_facility()
),returns 一个查询生成器对象,facility
函数未知.
你应该做的:
return $this->report_facility->facility
在这种情况下,eloquent 将为您提供 ReportFacility 模型,您可以从中检索设施 属性 或关系。
类似于:
return $this->report_facility()->first()->facility