I have two models: Persons and PhoneNumbers
Persons.php
class Persons extends Model
{
protected $table = 'persons';
protected $guarded = [];
public function phoneNumbers() {
return $this->hasMany('App\PhoneNumbers', 'persons_id', 'id');
}
}
PhoneNumbers.php
class PhoneNumbers extends Model
{
protected $table = 'phone_numbers';
protected $guarded = [];
public function persons() {
return $this->belongsTo('App\Persons', 'persons_id', 'id');
}
}
My tables:
1) persons (id, first_name, last_name, middle_name)
2) phone_numbers (id, person_phone, persons_id)
I have a form for search with first_name, middle_name, last_name, person_phone. I make a request:
$first_name = $request->first_name;
$middle_name = $request->middle_name;
$last_name = $request->last_name;
$persons = Persons::where('first_name', 'LIKE', '%' . $first_name . '%')
->where('middle_name', 'LIKE', '%' . $middle_name . '%')
->where('last_name', 'LIKE', '%' . $last_name . '%')
->whereHas('phoneNumbers', function (Builder $query) {
$person_phone = ((new \Illuminate\Http\Request)->get('person_phone'));
$query->where('person_phone', 'like', '%' . $person_phone . '%')->first();
})->latest()->paginate(5);
And get an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'persons.id' in 'where clause' (SQL: select * from
phone_numbers
wherepersons
.id
=phone_numbers
.persons_id
andperson_phone
like %% limit 1)
It seems that Laravel gives 'wrong' name for my columns and makes icorrect SQL. I know about naming conventions. But I can't find the error. Can you help me with making correct SQL with Eloquent?