Home > database >  Avoid loading all related records when performing a query on relation
Avoid loading all related records when performing a query on relation

Time:01-06

Hi have a many to one relationship between HistoricData (many) to HistoricDataGroup (one) as defined in the function "data" in the model below:

class HistoricDataGroup extends Model { use HasFactory;

protected $fillable = ["name", "token", "description"];

public function data()
{
    return $this->hasMany("App\Models\HistoricData");
}

public static function boot()
{
    parent::boot();

    static::deleting(function ($group) {
        $group->data()->delete();
        $group->workingData()->delete();
    });
}

}

In my controller function, I want to fetch the fields from HistoricDataGroup and some records from its related HistoricData model depending on there where clause applied to that data, and then return as json.

public function showChunk(Request $request)
{
    $historic_data_group = HistoricDataGroup::find($request->id);
    $result["group"] = $historic_data_group;
    $result["data"] = $historic_data_group->data->where(
        "id",
        "<",
        $request->candle_id
    );
    return response()->json($result);
 }

However, the data appears twice in the $result as all the related records are included as well as the filtered related data, as shown in the dd($result) screenshot below:

enter image description here

Is there a way to execute this without loading all the related records?

CodePudding user response:

You can use Eloquent resources to format what you send to the front-end.

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class HistoricDataGroupResource extends JsonResource
{
   public function toArray($request)
   {
    return [
        'id' => $this->id,
        // Map your other table data 
        
   }
}

in your controller

public function showChunk(Request $request)
{
   $historic_data_group = HistoricDataGroup::find($request->id);
   $data = $historic_data_group->data()->where("id", "<",$request->candle_id)->get();
       return response()->json([
          'group'=> \App\Http\Resources\HistoricDataGroupResource::make($historic_data_group),
          'data'=>$data
    ]);
  }

CodePudding user response:

You can use resources class for that and map everything you want

  •  Tags:  
  • Related