2014-02-23 42 views
0

我有一些表像如下:Laravel - 型號和功能

id 
name 
parent_id 
... 

的PARENT_ID是從同一個表本身的ID,因爲它是簡單的東西。例如:

id: 1 
name: abc 
parent_id: 0 

id: 2 
name: abc_parent 
parent_id: 1 

id: 3 
name: another 
parent_id: 1 

如何在該模型中的某個函數內獲取「名稱」?類似...

public function parentName() 
{ 
    $pid = this->parent_id; 
    /// return self::find($pid)->name; ### this does not actually work 
} 

我應該創建一個單獨的函數並將parent_id傳遞給它嗎?或者有沒有更簡單的方法?

回答

0

在你的模型中,定義父親relationship

class Model extends Eloquent { 
    public function parent() { 
    return $this->hasOne('Model', 'parent_id'); 
    } 
} 

這將允許您使用像$item->parent->name這樣的關係。

如果您想要類似$item->parentName的東西,您可以將attribute accessor作爲關係的別名。

public function getParentNameAttribute() { 
    return $this->parent->name; 
} 

然後你就可以做$item->parentName