繁体   English   中英

Laravel雄辩:具有条件级联的Model属性

[英]Laravel eloquent : Model attribute with conditional concatenation

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

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>)//如果不为null

现在,我的查询为:

public function getFullNameAttribute()
    {

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

但它返回:

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

我需要返回名称+ [“(abbrv)”] // // [value] =如果不为null

试试这个方法

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

尝试这个

public function getFullNameAttribute()
{
    if( ! $this->abbrv)
       return $this->name;

    return sprintf('%s (%s)', $this->name, $this->abbrv);

}

为**工作 :

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

您可以(ab)使用CONCAT()函数和串联运算符||之间的NULL差异。 ,即:

CONCAT(name, ' (' || abbrv || ')')

应该可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM