Php Laravel 5.6 API资源集合-未获取条件关系
我正在经历我的第一个Laravel项目,我实现了一个资源收集API,通过passport获取数据。数据似乎从模型中正确检索,关系除外。情况如下: item.php(模型) 或者通过在模型中明确外键:Php Laravel 5.6 API资源集合-未获取条件关系,php,laravel,laravel-5,Php,Laravel,Laravel 5,我正在经历我的第一个Laravel项目,我实现了一个资源收集API,通过passport获取数据。数据似乎从模型中正确检索,关系除外。情况如下: item.php(模型) 或者通过在模型中明确外键: /** * Componenti Correlati * Getter * @return object Componenti */ public function componenti() { // Definizione relazione return $this-&g
/**
* Componenti Correlati
* Getter
* @return object Componenti
*/
public function componenti()
{
// Definizione relazione
return $this->belongsTo('App\Componente', 'componente_id');
}
我还没有恢复关系。
有人能给我一点帮助/提示来解决这个问题吗
提前感谢您的帮助。以下代码仅在显式加载Tipologie时显示,以避免N+1查询问题
'tipologie' => TipologiaResource::collection($this->whenLoaded('tipologia'))
要加载Tipologie以便资源显示它,您需要显式地将其加载为:
$itemResource = new ItemResource($item->load('tipologia', ... other relationships...);
有关此操作的更多信息,请参阅
编辑
很抱歉,我们不理解这种关系的类型,正如@luca cattide所说,集合不应该用于belongsTo,正确的方法是使用:
TipologiaResource::make($this->tipologia);
或者:
new TipologiaResource($this->topologia);
但我建议您在加载之前使用“加载”方法来加载信息,否则您将在数据库中搜索“项”,再搜索“类型”等等,直到加载所有关系
还有一种方法可以在不必加载项目的情况下加载信息,请参见以下内容:
new ItemResource(App\Item::find(1)->with(['tipologie', ... other relationships ... ])->get());
查看更多关于N+1查询问题的信息。谢谢@vinicius,但正如@CamiloManrique所建议的那样,我注意到,在这些关系中,我试图从
属于
方面获取数据(实际上是从项
而不是从组件
,Tipologia
等等)。按原样::collection
根本不起作用,除非由hasMany
关系方调用
因此,当加载时,我将::collection
与结合使用
// Resoruce - Straight including relations instead of lazy load
[...]
'componenti' => ComponenteResource::collection($this->componenti),
[...]
// Includi associazioni se caricate
'componente' => ComponenteResource::make($this->componente),
'condizione' => CondizioneResource::make($this->condizione),
'fornitore' => FornitoreResource::make($this->fornitore),
'locazione' => LocazioneResource::make($this->locazione),
'tipologia' => TipologiaResource::make($this->tipologia)
以这种方式获取数据时不会出错
再次感谢你的提示
new ItemResource(App\Item::find(1)->with(['tipologie', ... other relationships ... ])->get());
// Includi associazioni se caricate
'componente' => ComponenteResource::make($this->componente),
'condizione' => CondizioneResource::make($this->condizione),
'fornitore' => FornitoreResource::make($this->fornitore),
'locazione' => LocazioneResource::make($this->locazione),
'tipologia' => TipologiaResource::make($this->tipologia)