I deal with the following situation: I have two models: Employee with fields id and name and Telephone with fields id , employee_id and flag . There is a one-to-many relationship between the two models, that is, an employee can have many phones, and a phone can belong to one employee.
class Employee extends Model { public function telephones() { return $this->hasMany(Telephone::class); } } class Telephone extends Model { public function employee() { return $this->belongsTo(Employee::class); } }
The Employee model refers to the employees table, which exists in the database schema named mydb1 , and the Telephone model refers to the telephones table, which exists in another database schema named mydb2 .
I want to get only employees with at least one phone of a certain flag loaded using Eloquent and (if possible), and not a query designer
I have tried so far without success:
1) use the whereHas method in the controller
$employees = Employee::whereHas('telephones', function ($query) { $query->where('flag', 1); //Fetch only the employees with telephones of flag=1 })->with([ 'telephones' => function ($query) { //Eager load only the telephones of flag=1 $query->where('flag', 1); } ])->get();
What I'm trying to do here is to first get only employees who have phones with flag = 1, and secondly, to load only these phones, but I get the following request exception due to different db:
Base table or view not found: Table mydb1.telephones does not exist (it is true, phones exist in mydb2)
2) Terrible load with restrictions in the controller
$employees = Employee::with([ 'telephones' => function ($query) { $query->where('flag', 1); }, ])->get();
This method loads phones with flag = 1, but it returns all instances of employees, which I really don't want. I would like to have a collection of only models of employees who have phones with flag = 1, except for models with telephones = []