有没有办法使用访问器来更改Laravel 4中某个查询的字段?所以,我有一个模型,“Fanartist.php”。在另一张表“艺术家”中,我有字段“描述”。我通过查询函数中的连接来调用它。这是功能:
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();
}
我正在尝试使用以下内容更改此特定查询函数的“description”字符串:
public function getDescriptionAttribute($value) {
return substr($value, 0, 90);
}
我是将它添加到Fanartist模型还是Artist模型?此外,如何使用此访问器仅影响此特定查询功能的描述字段?我希望描述保持不变以用于其他目的和查询。谢谢你的帮助。
答案 0 :(得分:0)
我不认为Eloquent的访问者/ mutator会帮助您进行自定义查询,例如您指定的查询。作为替代方案,您可以尝试这样的事情:
$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();
然后,出于此查询的目的,艺术家描述将是缩短版本。