Home > other >  hasMany relationship and where clause
hasMany relationship and where clause

Time:10-19

I have a hasMany relationship on ModelA thats is linked to ModelB. In my query, I have a where clause where I look for specific information in ModelB relationship.

Everything is fine if the relationship is found between ModelA and ModelB but if there is no relationship between ModelA and ModelB I get an error that specific column (from ModelB) was not found.

I already tried various methods to check if the relationship is present without no success (including: has(), relation()->exists()).

I could append attribute and filter out results after executing the query but with this approach my pagination numbers get messed up.

Anything I can do to check if the relationship exists before running the query?

CodePudding user response:

Use this method to check if model relation exist or not:

if (count($model->relation))
{
  // exists
}

CodePudding user response:

Try this;

$result = ModelA::whereIn('relation_id', ModelB::where('column', $data)->pluck('id')->toArray())->get();
  • Related