Romnick Susa
Romnick Susa

Reputation: 1288

Laravel 5.2 : Accessing relationship method from the other relationship method

i am trying to access the relationship in laravel relationship from other relation of my Entity model but i am getting a wrong return.

class Entity{


public function company()
{
    return $this->hasOne('App\Models\Company' , 'company_code' , 'company_code' );
}

public function branch(){
    $company = $this->company; // wrong return
    return $this->hasOne('App\Models\Branch' , 'company_code' , 'company_code' )
        ->where( 'company_id' , $company->company_id );
}

public function getTestAttribute(){
    $company = $this->company // correct return
    return $company->company_id;
}

The $this->company is returning the first item of company model instead of its relationship when i am trying to access it on my branch() method. Is there a way to access company() method in other relationship method with a correct value? I can access it on my Accessor method so i am expecting to access it too.

Upvotes: 2

Views: 513

Answers (2)

Keshari Nandan
Keshari Nandan

Reputation: 1148

Try putting the condition in following way -

public function branch(){
    $companyId = $this->company->company_id;
    return $this->hasOne('App\Models\Branch' , 'company_code' , 'company_code' )
        ->where( 'company_id', '=', $companyId );
}

Upvotes: 0

YouneL
YouneL

Reputation: 8351

I think that laravel call relation ship methods when the app started to define relation between tables, during this time $this reference nothing, I suggest you to move branch relation to the Company model:

class Company{

    public function branch() {

        return $this->hasOne('App\Models\Branch' , 'company_code' , 'company_code' );

    }

}

Now you can get branch from the Entity by using:

$this->company()->branch

Upvotes: 2

Related Questions