Search code examples
laraveleager-loadingrelation

Laravel relation doesn't load through with method for an attribute


I have 3 tables contracts, details and extra.

Each contract has a detail with a foreign key named contractId inside details table.

Each detail has 5 columns that is from extra table named Color,... I define a hasOne relation in contract model and a belongs to relation in detail model which is working fine.

I define a relation so I can get color of each contract through detail model in detail:

public function carColor(): BelongsTo
{
    return $this->belongsTo(Extra::class, "ColorCode", "id")->where('type', Extra::COLOR->value);
}

In my function, I wrote this to retrieve a contract model with its detail and inside detail I load extra, but in result I'm just getting id not name:

return ThirdPartyContract::where('id', $id)
    ->with(['detail' => function ($query) {
        $query->with(['carColor' => function ($query) {
            $query->select('name');
                }]);
            }])
        ->with('people')
        ->get();

Solution

  • Why not simply have many to many with colors table and colors table will have id, name and type of the color? It's an easy refactor to do so, but anyways, you should fetch id and name from the Extra model (table):

    return ThirdPartyContract::where('id', $id)
        ->with(['detail' => function ($query) {
            $query->with(['carColor' => function ($query) {
                // Select the necessary columns from the 'extra' table
                // You can add more columns if you want, it's important to have id so you can fetch data from the related tables
                $query->select('id', 'name'); 
            }]);
        }])
        ->with('people')
        ->get();