Home > Software engineering >  Laravel return empty when eager child relationship is empty
Laravel return empty when eager child relationship is empty

Time:11-08

I am trying to fetch the data from table name pos_receipt. It has a child table which contains a column receipt_id of pos_receipt primary key. I just want to return empty if child table has no relationship with parent table. Right now its returning the data with empty array of parent if there is no relationship. It should return empty array if there is no relationship in child table

Here is the query :

 $options = PosReceipt::with([
                    'transferBranch' => function ($query) {
                        $query->where('branch_id',2);
                    },
                ])
                ->where('receipt_no','LIKE','%'.$filters->keyword.'%')
                ->whereDate('receipt_date','>=', $date1)
                ->whereDate('receipt_date','<=', $date2)
                ->where('type', 'TRN')
                ->limit(20)
                ->offset($request->start)
                ->orderBy('id','DESC')
                ->get();

AND THE RELATIONSHIP FOR THE MODEL FOR transferBranch relation is //MODEL CALSS OF PosReceipt

public function transferBranch()
{   
    return $this->hasMany(TransferStore::class,'receipt_id');
}

CodePudding user response:

The hasMany method has 3 arguments.

/**
 * Define a one-to-many relationship.
 *
 * @param  string  $related
 * @param  string|null  $foreignKey
 * @param  string|null  $localKey
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function hasMany($related, $foreignKey = null, $localKey = null)

Try changing to

 return $this->hasMany(TransferStore::class,'receipt_id','id');

And make sure youre using this at the top of the model.

use Illuminate\Database\Eloquent\Relations\HasMany;

CodePudding user response:

incase if someone needs a solution

$options = PosReceipt::with([
                'transferBranch'
            ])
            ->whereHas("transferBranch",function($q) use($filters){
                $q->where("branch_id","=",$filters->storeID);
            })
  • Related