How to use an accessor in Laravel 4 that only affects a field in a certain query function

StackOverflow https://stackoverflow.com/questions/18197858

  •  24-06-2022
  •  | 
  •  

Вопрос

Is there a way to use an accessor to change a field for only a certain query in Laravel 4? So, I have a model, "Fanartist.php". In another table, "artists", I have the field "description". I am calling it with a join in a query function. This is the function:

public static function fan_likes_json() {
        $fan_likes = DB::table('fanartists')
                    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
                    ->where('fanartists.fan_id', '=', Auth::user()->id)
                    ->select('artists.id', 'artists.stage_name', 'artists.city', 'artists.state', 'artists.image_path', 'artists.description')
                    ->get();  

}

I am trying to change the "description" string for this specific query function, using something like this:

public function getDescriptionAttribute($value) {

        return substr($value, 0, 90);

    }

Do I add this to the Fanartist model, or the Artist model? And also, how do I have this accessor only affect the description field for this specific query function? I would like the description to remain unaltered for other purposes and queries. Thank you for your help.

Это было полезно?

Решение

I don't think Eloquent's accessors/mutators will help you for a custom query like the one you've specified. As an alternative, you could try something like this:

$fan_likes = DB::table('fanartists')
    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
    ->where('fanartists.fan_id', '=', Auth::user()->id)
    ->select(DB::raw('substring(artists.description, 1, 90) as description, artists.id, artists.stage_name, artists.city, artists.state, artists.image_path'))
    ->get();

Then, for the purpose of this query, the artist description will be the shortened version.

See: MySQL SUBSTRING and Raw expressions in Laravel 4

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top