1

I have this model:

class Payment extends MyBaseModel
{  
    protected $table = 'payments';
    protected $with = ['company', 'account', 'manager', 'block', 'network'];
    protected $appends = ['someAttribute', 'someOtherAttribute'];

   ...
}

In another model I have a relation that looks like this:

public function payment() {
      return $this->belongsTo('App\Payment', 'payment_id', 'id')->withTrashed();
}

What I need is to be able to, sometimes, retrieve $this->payment without all the the relationships specified in $with (i.e. company, account, manager, block, network) also would like to (sometimes) disable the appended attributes.

Can't find a way to accomplish that. I've tried the following with no luck.

public function payment() {
    $this->belongsTo('App\Payment', 'payment_id', 'id')->setEagerLoads([])->withTrashed();
}
Stephen H. Anderson
  • 978
  • 4
  • 18
  • 45

2 Answers2

0

Maybe something like below help you to dynamically disable eager loading on relationship

OtherModel::with(['payment'=>function($query){
    $query->setEagerLoads([]);
}])->get();
SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32
0

I think you have to iterate over the model collection and setAppends because setAppends and hidden can't work for belongsTo or hasMany relationship. Here is my idea.

contoller.php

$exceptRelationships = ['company', 'account', 'manager', 'block', 'network'];
$setAppends = ['someAttribute'];

$payments = $anotherModelInstance->payment($exceptRelationships)->get();

// foreach on each payment and set required appends.
// if you don't want any then simply set empty array.
$payments->each(function ($payment, $key) use ($setAppends) {
        $payment->setAppends($setAppends);
        // $payment->setAppends([]);
    }
); 

AnotherModel.php

public function payment($without = [])
{
    return $without ? $this->belongsTo('App\Payment', 'payment_id', 'id')->withTrashed()->without($without) : $this->belongsTo('App\Payment', 'payment_id', 'id')->withTrashed();
}
Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47