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.