Chandni Soni
Chandni Soni

Reputation: 387

How to use Eloquent column name out of with() block in laravel 5.6?

I want to use eloquent column name out of with block.
I have tried relationFunctionName.colun_name and tableName.column_name but it gives me an error. no such column exists.

My query:

$d = FormsValues::select('forms_values.id', 'forms_values.patient_id','forms_values.doctor_id')
                    // ->with('getUserPatientAssinged')
                    ->with(array('getUserPatientAssinged' => function($query) use($user) {
                        $query
                        ->select('form_value_id','consultation_assigned_by','date as consultation_date', 'start_time as consultation_start_time', 'end_time as consultation_end_time','doctor_id')
                    }));

--Some other code---

$d = $d->where('getUserPatientAssinged.doctor_id', Auth::user()->id);

Any Solution?
Thank you

Upvotes: 1

Views: 261

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

Typically, you cannot use the columns of a relationship outside of a ->with() clause unless you also use a ->join(). For example:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->where('assigned_patients.doctor_id', auth()->user()->id)
->get();

Note: Assuming some table names, as you would reference that instead of the relationship name

The above code would likely throw an error around assigned_patients.doctor_id being an unknown column, as it is unavailable in the current scope. This can be solved by using a ->join() along with the ->with() clause:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->join('assigned_patients', ...)
->where('assigned_patients.doctor_id', ...)
->get();

Alternatively, we can use ->whereHas() as long as the relationships are constructed. For this, we're looking for the Doctor of the "assigned patient", so:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->whereHas('getUserPatientAssigned.doctor', function ($query) {
  return $query->where('id', auth()->user()->id);
})->get();

Upvotes: 1

Related Questions