1

I meet this problem: I have model of people and model of their activities and I want to declare relation like latest activity inside of person model but Laravel does not give permission to use 'Limit' or 'Take' inside of Eager Loads

So how it could be done ?

I tried this inside of person model

public function lastActivity()
{
    return $this->belongsToMany('App\Models\Activity','activity_job','job_id','activity_id')
                ->orderByDesc('created_at')->limit(1);
}

But it takes latest activity of one person not for all Please Help

Hyzyr
  • 568
  • 4
  • 13

1 Answers1

1

Let's say you have a model Person (or People, whatsoever...)

(Person.php)

class Person extends Model {

    protected $table = 'persons';


    public function activities()
    {
        return $this->hasMany(Activity::class);
    }

    ...
}

And a model Activity (Activity.php)

class Activity extends Model {

    ...

    public function person()
    {
        return $this->belongsTo(Person::class);
    }

    ...
}

Now to get all Persons with their latest activity

Person::with(['activities' => function ($query) {
        $query->orderBy('id', 'desc');
    }])->get()
       ->map(function ($person) {
            $person->setRelation('activities', $person->activities->take(1));
            return $person;
        });

Explanation: We get all Persons with all of their activities. Then we map through the collection and (re)set the activities relationship with only one item of the activities collection. Because we ordered the activities by id in descending order, take(1) will give us the persons latest activity.

NICO
  • 1,695
  • 1
  • 12
  • 11
  • It is pending too long and gives error like : _"Allowed memory size of 536870912 bytes exhausted (tried to allocate 8388616 bytes)"_ – Hyzyr May 23 '21 at 14:35
  • Using the Laravel Debugbar displaying 10.000 people with 40.000 activities takes ~1.37s having a memory usage of 83 MB. Displaying 20 entries with pagination takes ~28ms with a memory usage of ~6MB – NICO May 23 '21 at 15:20
  • Check the memory limit in your php.ini or paginate your results. Maybe you have an error elsewhere in your code. – NICO May 23 '21 at 15:37