nyel-dev
6 months ago

Modify laravel relationship eager loading

Posted 6 months ago by nyel-dev

I have this relationship in my model:

    class Job extends Model
    {
        public function xref() {
            return $this->hasOne('App\Test', 'id', 'job_id');
        }
    }

and I am calling it on my controller like this:

    $jobs = Job::with('xref')->get();

I was wondering, how can I make a condition inside the model relationship. Like if the relationship xref returns null. I was hoping I could do something like this:

    class Job extends Model
    {
        public function xref() {
            $xref = $this->hasOne('App\Test', 'id', 'job_id');

            if($xref == null) {
                $xref = $this->hasOne('App\NewTest', 'id', 'job_id');
            }

            return $xref;
        }
    }

so basically what I want is check if what I am returning is null and if null, call a new relationship to another table.

Is this possible somehow?

Please sign in or create an account to participate in this conversation.