Dave Wize's avatar

relationship returns null

This code works

    public function accountTelephone(): HasMany
    {
        return $this->hasMany(AccountTelephone::class, 'telephone_no', 'telephone_no');

    }

But if I add this where clause it breaks, no idea why

    public function accountTelephone(): HasMany
    {
        return $this->hasMany(AccountTelephone::class, 'telephone_no', 'telephone_no')
            ->where('area_code', $this->area_code);

    }
0 likes
1 reply
LaryAI's avatar
Level 58

The issue with the code is that the where clause is using $this->area_code which is not accessible within the relationship method. To fix this, you can use a closure to pass the $this->area_code value to the where clause. Here's an updated version of the code:

public function accountTelephone(): HasMany
{
    return $this->hasMany(AccountTelephone::class, 'telephone_no', 'telephone_no')
        ->where(function ($query) {
            $query->where('area_code', $this->area_code);
        });
}

By using a closure, you can access the $this->area_code value within the where clause.

Please or to participate in this conversation.