Data is not received in relation to whereHas Laravel

Viewed 721

I've been trying to query whereHas and I can't retrieve the data. Look how I tried. I made a whereHas where I have a query function after I put another where how to take the data. Keep in mind that where refers to bias and not discount_codes

public function showPopupData(Request $request)
    {
        $id = Auth::user()->company_id;

        $data = Popup::getPopupByCompanyId($id);

        $biases = Bias::whereHas('discount_codes', function ($query) {
            $query->where('discount_code.id', '=', 'bias.discount_code_id');
        })->get();
       

        return response()->json(['data' => $data, 
                        'biases' => $biases
                        ]);
    }

It should be maintained that, with the next relationship, I also receive the data for which I have a relationship.

 $biases = Bias::with('discount_codes')->where('company_id', '=', $id)->get();

Models

public function discount_codes()
    {
        return $this->belongsTo('App\Models\DiscountCode', 'discount_code_id', 'id');
    }
 public function biases() 
    {
        return $this->hasMany('App\Models\Bias', 'id', 'discount_code_id');
    }

Tables

Discount code
$table->increments('id');
            $table->string('discount_code')->nullable();
Bias
 $table->integer('discount_code_id')->nullable()->unsigned();
 $table->foreign('discount_code_id')->references('id')->on('discount_codes')->onDelete('cascade');

What do you think I'm doing wrong here?

3 Answers

I think you can use has()

$biases = Bias::with('discount_codes')->has('discount_codes')->get(); 

You don't need the relation "whereHas" condition here, because the "has" function does the same thing that you are trying to achieve here, just simply use the "has" operator.

$biases = Bias::has('discount_codes')->get();

first of all, your code is redundant.

Bias::whereHas('discount_codes', function ($query) {
    $query->where('discount_code.id', '=', 'bias.discount_code_id');
})->get();

you have already joined both tables using the primary key and foreign key by calling relationship. you don't have to check id again.

so simple with just work fine

$biases = Bias::with('discount_codes')->where('company_id', $id)->get();

now if you want only those records which have discount_codes you can check relationship existence with has

$biases = Bias::has('discount_codes')->with('discount_codes')->where('company_id', $id)->get();

now in your bias relationship you have put the keys in the wrong way. it should be

public function biases() 
{
    return $this->hasMany('App\Models\Bias', 'discount_code_id', 'id');
}

and finally you have messed the naming conventions. you should consider following the standard naming conventions.

Related