1

I have connected tables with a hasMany & belongsTo relationship.

Bridal Model:

public function plans()
{
    return $this->hasMany("App\Plan");
}

Plan Model:

public function bridal()
{
    return $this->belongsTo("App\Bridal");
}

And I have an query that returns those data to endpoint.

public function bridal()
{

    $bridals = Bridal::with(["plans" => function($query){
        $query->orderBy("plans.plan_price");
    }])
    ->groupBy("place_name")
    ->get();


    return $bridals;

}

Everything is fine, except one thing. In Bridal table some of ID doesn't have plan. So when I return datas, some of bridal id comes with an empty Plans array.

enter image description here

I want to prevent that. If a bridal id doesn't have a plan, then I don't want to return that bridal id. How can I achieve what I want here?

yvl
  • 620
  • 7
  • 25

2 Answers2

2

You can use Has. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

$bridals = Bridal::with(["plans" => function($query){
        $query->orderBy("plans.plan_price");
    }])->has('plans')
    ->groupBy("place_name")
    ->get();

Check more info SO answer

lagbox
  • 48,571
  • 8
  • 72
  • 83
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
1

Add whereHas() in your query : so you will get bridal records which has plans

$bridals = Bridal::with(["plans" => function($query){
       $query->orderBy("plans.plan_price");
   }])
   ->whereHas('plans')
   ->groupBy("place_name")
   ->get();
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53