【问题标题】:Laravel eloquent : Model attribute with conditional concatenationLaravel 雄辩:具有条件连接的模型属性
【发布时间】:2017-11-19 02:53:20
【问题描述】:

我有一个表(比如 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)
 }
]

即字符串连接:

  • //强制

  • ( ) //如果不为空

现在,我的查询是:

public function getFullNameAttribute()
    {

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

但它会返回:

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

我需要返回 name + ["(abbrv)"] // where [value] = if not null

【问题讨论】:

    标签: php postgresql laravel eloquent concatenation


    【解决方案1】:

    试试这个方法

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

    【讨论】:

      【解决方案2】:

      试试这个

      public function getFullNameAttribute()
      {
          if( ! $this->abbrv)
             return $this->name;
      
          return sprintf('%s (%s)', $this->name, $this->abbrv);
      
      }
      

      【讨论】:

        【解决方案3】:

        曾就职于:

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

        【讨论】:

          【解决方案4】:

          您可以(ab)使用NULL 处理CONCAT() 函数和连接运算符|| 之间的差异,即:

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

          应该可以解决问题。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-02-07
            • 1970-01-01
            • 2021-08-11
            • 2022-01-15
            • 1970-01-01
            • 2021-12-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多