Miura-shi
Miura-shi

Reputation: 4519

Get Collection With HasOne Relationship

In my User model in Laravel 5.2 I have a relationship setup with their status to the company.

public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status');
}

The CompanyUser table has a company_id, user_id, and status field

Then in my controller I do the following:

$company   = Company::find($company_id);
$users     = CompanyUser::where('company_id', $company_id)->pluck('user_id')->toArray();
$user_data = User::with('companyStatus')->find($users);

but when I dump the user_data array it has all of the users related to the company, but just shows null for their status relationship

{
   "id":2,
   "name":"Moderator",
   "email":"[email protected]",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status":null
 }

If I however return just the User collection to the view, and iterate over each user and run

$user->companyStatus->status 

the value displays, but I am trying to include this within the collection for a JSON API to consume.

UPDATE

I tried adding the foreign key to the select call on my relationship method:

public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status', 'user_id');
}

and it now returns the following:

{
   "id":2,
   "name":"Moderator",
   "email":"[email protected]",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status": {"status":"1","user_id":"2"}
 }

Not sure if this is the best/correct method or not though.

Upvotes: 3

Views: 1991

Answers (1)

Miura-shi
Miura-shi

Reputation: 4519

Okay I figured it out.

I tried adding the foreign key to the select call on my relationship method:

public function companyStatus()
{
    return $this->hasOne('CompanyUser')->select('status', 'user_id');
}

Then that returns:

{
   "id":2,
   "name":"Moderator",
   "email":"[email protected]",
   "created_at":"2016-09-08 15:26:20",
   "updated_at":"2016-09-08 15:26:25",
   "company_status": {"status":"1","user_id":"2"}
}

Without the foreign key Laravel obviously can't determine the related data on the other table.

Upvotes: 3

Related Questions