Sunday, April 16, 2017

Eloquqent: LIKE with polymorpic models

Database

I have customers table

id | concrete_id | concrete_type 

customers_person table

id | person_id

customers_entity table

id | entity_id 

person table

id | firstname | lastname

Models

Model Customer defined with

public function person()
{
    return BelongsToMorph::build($this, CustomerPerson::class, 'concrete');
}

BelongsToMorph realization here (Eloquent don't have it default).

And i can get all Customers as Person, it's well work:

Customer::whereHas('person')

My question is: how to get Only those Persons, which contain 'foo' in the lastname?

I try this solution, but it's return only one record (I don't understand why it's happening).

Customer::whereHas('person', function ($query) {
      $query->join('persons', 'persons.id', '=', 'customer_persons.id')
          ->where('persons.lastname', 'like', '%Foo%');
});

This request native SQL look's like this:

    SELECT *
    FROM `customers`
    WHERE EXISTS (
    SELECT *
    FROM `customer_persons`
    INNER JOIN `persons` ON `persons`.`id` = `customer_persons`.`id`
    WHERE `customers`.`concrete_id` = `customer_persons`.`id` 
    AND `customers`.`concrete_type` = 'customer_person' 
    AND `persons`.`lastname` LIKE "%Foo%")



via Stanislav

Advertisement