pilat

with() does not work if I use where() in relations

Posted 1 year ago by pilat

Hi, I've stumbled over this issue.

Laravel 5.3

Here's couple of examples:

class Activity extends Model
{
    public function custom_fields()
    {
        return $this->hasMany(\App\CustomField::class, 'element_id', 'element_id');
    }

    public function lead()
    {
        return $this->hasOne(\App\AmoLeadsCache::class, 'id', 'element_id');
    }
}

class Activity extends Model
{
    public function custom_fields()
    {
        return $this->hasMany(\App\CustomField::class, 'element_id', 'element_id')
            ->where('custom_fields.subdomain', $this->subdomain);
    }

    public function lead()
    {
        return $this->hasOne(\App\AmoLeadsCache::class, 'id', 'element_id')
            ->where('leads_cache.subdomain', $this->subdomain);
    }
}

Now, in client's code I do the following:

Activity::with('custom_fields', 'lead')->where(/*some other cond*/)->get();

It works as expected if I don't have ->where() in the "relations" methods. If i have, however, all relations are empty (lead=>null, custom_fields=>[]).

Anyone knows how to overcome this? I really need to preserve those ->where() clauses, but I also need eager loading.

Please sign in or create an account to participate in this conversation.