Laravel Polymorphic Limit Related Records

111 Views Asked by At

I have two models that I am working with - Traffic and Account. These two models have a polymorphic relationship as through an accountables table all with standard Laravel conventions. An Account may belong to multiple traffics and other types of models.

I am trying to build an Account table with pagination that will show the latest Traffic model for each account.

I have tried to do this with a relationship on the Account model below -

    public function traffic(): MorphToMany
    {
        return $this->morphedByMany(Traffic::class, 'accountable')
            ->latest()
            ->limit(1);
    }

Then in my Account Table I am querying the accounts as such -

$query = Account::query()
    ->with('traffic')
    ->when($this->filters['search'], function ($query, $search) {
        $query
            ->where('name', 'LIKE', '%' . $search . '%');
    });

This works for the LAST and only last account on the table. If I change the ->with('traffic') statement to ->withCount('traffic') I will get the last traffic for each Account however introduce N+1 issue.

I have also tried hasManyThrough and other methods without success.

How can I retrieve just one traffic model for each account that is on the table?

Thank you for any help.

1

There are 1 best solutions below

0
moemen gaballa On

I am not sure but you can try this.

public function traffic(): MorphToMany
    {
        return $this->morphedByMany(Traffic::class, 'accountable');
    }

$account = Account::query()->when($this->filters['search'], function ($query, $search) {
    $query
        ->where('name', 'LIKE', '%' . $search . '%');
})->first();


$traffic = $account->traffic()->paginate(10);



return view('example', compact('account', 'traffic'));