2017-06-16 78 views
0

我有一個表(說myreferencetable)與名單as..say:Laravel雄辯:有條件的級聯模型屬性

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)」] //其中[值] =如果不爲空

回答

3

嘗試此方法

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

試試這個

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

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

} 
0

就職於:

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

請使用「thx」的註釋;) – Dmitry

0

你可以(AB)使用CONCAT()功能和連接運算符||,即:

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

之間的NULL - 處理分歧應該做的伎倆。