Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

use this: http://laravel.com/docs/5.0/eloquent#accessors-and-mutators

or perhaps do it in a repository pattern

0

may be you're looking for a presenter pattern ? https://github.com/robclancy/presenter

0

Ah thanks for reply!

You know, I use mutators and presenters (from laracasts lesson).

The thing I'm concerned is that if I put a getProgress method in my eloquent class, and then I'll loop through users, I'll get a lot of queries. Getting progress is quite complicated, it requires right now 3-4 joins. So the general question is: if I have some big logic concealed into this small progress() method, how can I deal with it so that I don't have a lot of queries?

Right now I have a user repository with getProgress method which is like this (maybe not optimized at all but...):

    public function getVisitProgress($usersId, $since, $till)
    {
        $params = [
            'CRM\EloquentModels\Contact',
            'CRM\EloquentModels\Touch',
            $since,
            $till,
            join(',', $usersId)
        ];

        return \DB::select("select users.last_name, ifnull(sum(t1.has_visits), 0) as progress
                            from users
                            left join (
                                select contacts.user_id as user_id, if(count(touches.id) >= 1, 1, 0) as has_visits
                                from contacts
                                left join activities on activities.activitable_id = contacts.id
                                left join touches on touches.id = activities.child_id
                                where activities.activitable_type = ? and
                                      activities.child_type = ? and
                                      touches.created_at between FROM_UNIXTIME(?) and FROM_UNIXTIME(?)
                                group by contacts.id
                            ) as t1
                            on t1.user_id = users.id
                            where users.id in (?)
                            group by users.id", $params);
    }

Then I got an array of data, like user last name and progress, and display it. But after learning about repositories and other stuff, in L5 all my functions is no more than a couple of lines of code, and now I face this ugly SQL query, so I'm thinking how to simplify things

I thought about to load some data behind the scenes and then somehow give the user model access to it, so kind of eager loading.

Thaanks!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Victor victor Joined 18 Nov 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.