gpt4 book ai didi

php - Laravel Eloquent : Model attribute with conditional concatenation

转载 作者:行者123 更新时间:2023-11-29 12:35:45 26 4
gpt4 key购买 nike

我有一个表(比如 myreferencetable),名称列表为..say :

id    |    name   |   abbrv
- - - - - - - - - - - - - - - - -
1 | ABCDEF | abc
2 | TestState |
3 | UVWXYZ | xyz

在我的模型中,我为模型创建了一个属性:

protected $appends = [
'full_name'
];

现在,我想查询数据库,以便获得详细信息:

[
{
"name" : ABCDEF
"full_name" : ABCDEF (abc)
},
{
"name" : TestState,
"full_name" : TestState
},
{
"name" : UVWXYZ,
"full_name" : UVWXYZ (xyz)
}
]

即字符串连接:

  • //必填

  • ( < abbrv > )//如果不为空

现在,我的查询是:

public function getFullNameAttribute()
{

return MyReferenceTable::select(DB::raw('concat(name," (", abbrv, ")")'));
}

但它返回:

[
{
"name" : ABCDEF
"full_name" : {}
},
{
"name" : TestState,
"full_name" : {}
},
{
"name" : UVWXYZ(xyz)
"full_name" : {}
}
]

I need to return name + ["(abbrv)"] // where [value] = if not null

最佳答案

试试这个方法

public function getFullNameAttribute()
{
return $this->name . ($this->abbrv ? ' (' . $this->abbrv . ')' : '');
}

关于php - Laravel Eloquent : Model attribute with conditional concatenation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44587371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com