2017-09-13 52 views
0

我試圖從返回的數據中獲得關係。雄辯地訪問Laravel中的相關數據

在用戶

public function folders() 
{ 
    return $this->hasMany("App\Folder"); 
} 

public function rootFolder() 
{ 
    return $this->folders()->where("parentid", null); 
} 

在文件夾

public function subFolders() { 
    return $this->hasMany("App\Folder", "parentid"); 
} 

public function parentFolder() 
{ 
    return $this->belongsTo("App\Folder", "parentid"); 
} 
在控制器

$root = auth()->user()->rootFolder; 
$subs = $root->subFolders; 
foreach ($subs as $sub) { 
    echo $sub->name; 
} 

我越來越

Property [subFolders] does not exist on this collection instance. 

但是,如果

$root = new Folder; 

異常消失。

我必須以某種方式告訴從rootFolder函數返回的數據,你是一個文件夾?

回答

0

該函數返回的查詢:

public function rootFolder() 
{ 
    return $this->folders()->where("parentid", null); 
} 

所以這個人試圖訪問「子文件夾」查詢的屬性:

$root = auth()->user()->rootFolder; 
$subs = $root->subFolders; 

這種變化將努力返回一個文件夾對象:

public function rootFolder() 
{ 
    return $this->folders()->where("parentid", null)->first(); 
}