문제

A company hasMany users, this relationship is achieved through a pivot table. I want to be able to get the company.ID of the company an individual user is related to:

$company_id = User::find(Auth()->$id)->companies->get('$id');

Unfortunately, I have also tried the pluck() method, but to no success. How can one retrieve a specific value from a formula like this?

도움이 되었습니까?

해결책

in your user model you should add the relationship belongsTo (if the user belongs only to one company)

public function company(){

    return belongsTo('company');
}

then you can get the id of the company like this

$user      = User::find($id);
$company   = $user->company;
$companyId = $company->id;

I hope this will be helpful

다른 팁

Well if the User can only be associated with one company, then your relationship should reflect this. Then you'd be able to use eager loading to do something like this:

// assumes the user is logged in
$user = Auth::user();

// assuming your relationship is set up correctly, you can do this:
echo $user->company->id;

You'd need to post the code relating to your models / relationships for a fuller answer, however.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top