簡體   English   中英

Laravel 5.6 API資源收集-未獲取條件關系

[英]Laravel 5.6 API resource collection - Conditional relation not fetched

我正在經歷我的第一個Laravel項目,並且實現了一個資源收集API,在其中我通過護照獲取數據。 除了關系外,似乎可以從模型中正確檢索數據。 情況如下:

item.php(模型)

<?php

// Definizione Namespace
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Classe Item
 */
class Item extends Model
{
    use SoftDeletes;

    // Dichiarazione Proprietà
    protected $table = 'item';
    protected $dateformat = 'Y-m-d';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'data_acquisto',
        'labeled',
        'estensione_garanzia',
        'stato',
        'data_dismissione',
        'note'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'codice',
        'serial',
        'componente_id',
        'tipologia_id',
        'condizione_id',
        'locazione_id',
        'fornitore_id',
        'parent_id'
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'data_acquisto',
        'data_dismissione',
        'deleted_at'
    ];

    /**
     * All of the relationships to be touched.
     *
     * @var array
     */
    protected $touches = [
        'componenti',
        'condizioni',
        'fornitori',
        'locazioni',
        'tipologie'
    ];

    /**
     * Scope query item figli
     * Getter
     * @param array $query Query
     * @return array Query
     */
    public function scopeFigli($query)
    {
        return $query->where('parent_id', '!=', null);
    }

    /**
     * Componenti Correlati
     * Getter
     * @return object Componenti
     */
    public function componenti()
    {
        // Definizione relazione
        return $this->belongsTo('App\Componente');
    }

    /**
     * Condizioni Correlate
     * Getter
     * @return object Condizioni
     */
    public function condizioni()
    {
        // Definizione relazione
        return $this->belongsTo('App\Condizione');
    }

    /**
     * Fornitori Correlati
     * Getter
     * @return object Fornitori
     */
    public function fornitori()
    {
        // Definizione relazione
        return $this->belongsTo('App\Fornitore');
    }

    /**
     * Locazioni Correlate
     * Getter
     * @return object Locazioni
     */
    public function locazioni()
    {
        // Definizione relazione
        return $this->belongsTo('App\Locazione');
    }

    /**
     * Tipologie Correlate
     * Getter
     * @return object Tipologie
     */
    public function tipologie()
    {
        // Definizione relazione
        return $this->belongsTo('App\Tipologia');
    }
}

item.php(資源)

<?php

// Definizione Namespace
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\Componente as ComponenteResource;
use App\Http\Resources\Condizione as CondizioneResource;
use App\Http\Resources\Fornitore as FornitoreResource;
use App\Http\Resources\Locazione as LocazioneResource;
use App\Http\Resources\Tipologia as TipologiaResource;

class Item extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        parent::toArray($request);

        return [
            'id' => $this->id,
            'codice' => $this->codice,
            'data_acquisto' => $this->data_acqisto,
            'serial' => $this->serial,
            'labeled' => $this->labeled,
            'estensione_garanzia' => $this->estensione_garanzia,
            'stato' => $this->stato,
            'data_dismissione' => $this->data_dismissione,
            'note' => $this->note,
            'parent_id' => $this->parent_id,
            // Includi associazioni se caricate
            'componenti' => ComponenteResource::collection($this->whenLoaded('componenti')),
            'condizioni' => CondizioneResource::collection($this->whenLoaded('condizioni')),
            'fornitori' => FornitoreResource::collection($this->whenLoaded('fornitori')),
            'locazioni' => LocazioneResource::collection($this->whenLoaded('locazioni')),
            'tipologie' => TipologiaResource::collection($this->whenLoaded('tipologie'))
        ];
    }
}

這是有關獲取數據示例的屏幕:

在此處輸入圖片說明

如上所示,沒有關系的痕跡。 通過像這樣建議地搜索和更改代碼:

// Resoruce - Straight including relations instead of lazy load
[...]
'componenti' => ComponenteResource::collection($this->componenti),
[...]

或通過在模型中明確顯示外鍵:

/**
 * 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 for Resource以顯示它,您需要將其顯式加載為:

$itemResource = new ItemResource($item->load('tipologia', ... other relationships...);

有關更多信息,請參見急切加載

編輯

很抱歉,您不了解關系的類型,就像@ luca-cattide所說的那樣,collection不應該用於belongsTo,正確的方法是使用:

TipologiaResource::make($this->tipologia);

或者:

new TipologiaResource($this->topologia);

但是我建議您先使用“加載”方法加載信息,否則,您將在數據庫中搜索“項目”,然后通過“ typologie”進行搜索,依此類推,直到加載所有關系。

還有另一種無需加載項目即可加載信息的方式,請參見下文:

new ItemResource(App\Item::find(1)->with(['tipologie', ... other relationships ... ])->get());

在此處查看有關N + 1查詢問題的更多信息。

謝謝@vinicius,但是像@CamiloManrique的這篇文章中所建議的那樣,進行了更多地搜索,我注意到在這些關系中,我試圖從belongs_to端獲取數據(因此實際上是從Item而不是ComponenteTipologia等獲取數據。上)。 就像::collection根本不起作用,除非由hasMany關系端調用

因此,代替將::collectionwhenLoaded結合使用,我進行了如下重構:

    // 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)

通過這種方式,可以正確無誤地獲取數據。

再次感謝您的提示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM