为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel getNameAttribute 不适用于搜索

Laravel getNameAttribute 不适用于搜索

PHP
明月笑刀无情 2023-03-04 14:50:17
我有Account模型,里面有这个方法:public function getNameAttribute(){    if(\App::getLocale() == 'en')        return $this->attributes['foreign_name'];    else        return $this->attributes['name'];}在索引页面中它正在工作。如果 locale 是enname 将是foreign_name,如下图:但是我有搜索方法,这是代码:public static function search_and_select($keyword){    $keyword = Helper::clean_keyword($keyword);    $data = Account::where    ('number','like','%'.$keyword.'%')->    orWhere('name','like','%'.$keyword.'%')->    limit(30)->    get(['user_id','number','name']);    if(count($data) == 0)        return Helper::no_result();    return [$data,['number','name']];       }如果我尝试搜索任何内容,我会收到此错误:message: "Undefined index: foreign_name"    1: {,…}class: "App\Models\Account"file: "C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php"function: "getNameAttribute"line: 465type: "->"2: {,…}class: "Illuminate\Database\Eloquent\Model"file: "C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php"function: "mutateAttribute"line: 479type: "->"但如果我改变:return $this->attributes['foreign_name'];到return $this->attributes['id']; // or any integer field in the accounts table 它工作没有问题。在 Laravel 6 中,它和我一样工作,但现在我得到了这个错误。这里有什么帮助吗?
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

这是因为你的线

get(['user_id','number','name'])

哪个要求只获取这些列。您需要将 foreign_name 添加到此数组并使其成为

get(['user_id','number','name', 'foreign_name'])

根据 Laravel参考,get 函数接受列列表。

同样适用于其他功能


查看完整回答
反对 回复 2023-03-04
  • 1 回答
  • 0 关注
  • 174 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信