PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 10, 2022

[FIXED] Get Collection With HasOne Relationship

 February 10, 2022     eloquent, laravel-5     No comments   

Issue

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":"mod@company.com",
   "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":"mod@company.com",
   "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.


Solution

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":"mod@company.com",
   "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.



Answered By - Miura-shi
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing