CodeSleeve / stapler

ORM-based file upload package for php.
http://codesleeve.com
Other
538 stars 144 forks source link

Getting attachments with the query builder #152

Closed itsjustk closed 8 years ago

itsjustk commented 8 years ago

Hi All!

I have a function in my eloquent model that allows me to get the latest user:

$this->orderBy('created_at', 'DESC')->limit(1)->first(['username']);

This model uses the avatar example in the docs and everything works fine when I just use Eloquent statically, however when i get a user model through the above function I just keep getting the default url.

I was hoping to be able to use

->with('avatar') 
->avatar->url

etc, no but luck.

Thanks for any info :)

tabennett commented 8 years ago

You're getting the default url because you're only selecting the username column (which is a rather silly thing to do). Stapler has no way to know that a file has already been uploaded because you've stripped the columns out or the results. I understand that you're probably trying to be clever because you only need the username column, but consider how much difficulty this has caused you and there is really no measurable performance overhead from just fetching all of the columns? Just keep it simple and do something like this:

// Don't create instance methods for searching your database; That's a very poor use of Active Record.
// Create a static, class level method that fetches an instance:
public static function latestr()
{
    return static::orderBy('created_at', 'DESC')
        ->limit(1)
        ->first();
}

$latestUser = User::latest();
// now you have an eloquent model instance and can work with the stapler attachment:
echo $latestUser->avatar->url();