0

I have 2 models. The model Contract hasOne (relation) Company.

On Company model I have the following relation:

public function contracts()
{
    return $this->hasMany('App\Models\SGC\Contracts\Contract', 'held_by_company_id', 'id');
}

I'm trying to get all contracts associated to a company, but since the contract table has many columns, I want to retrieve only 2. When I execute a function on relations, the contracts came empty.

So, if I query everything on contracts, I get the company data and associated contracts:

$requested_company_data = Company::with('contracts')->findOrFail($request->company_id)->toArray();

Thinking on optimization and since I want 2 columns, I want to select 2 columns. When I do that, the relations cames empty, but it's false cause I know the company ID 2 has contracts.

$requested_company_data = Company::with([
    'contracts' => function ($query) {
        $query->select('id', 'contract_code');
    }
])->findOrFail($request->company_id)->toArray();

I don't really see the error... Can someone enlight me? Thanks.

hhelderneves
  • 925
  • 8
  • 24
  • This SO post may also help find the issue https://stackoverflow.com/questions/38172857/how-to-select-specific-columns-in-laravel-eloquent – hppycoder Mar 12 '21 at 13:03

1 Answers1

0

You can specify columns with with:column1,column2 since Laravel 5.5:

$requested_company_data = Company::with('contracts:id,contract_code')
            ->findOrFail($request->company_id)
            ->toArray();
ibrahim-dogan
  • 621
  • 1
  • 5
  • 14