我试图从返回的数据中获取关系。
用户中的
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 :(得分:0)
此函数返回一个查询:
public function rootFolder()
{
return $this->folders()->where("parentid", null);
}
所以这个人试图访问" subFolders"查询的属性:
$root = auth()->user()->rootFolder;
$subs = $root->subFolders;
此更改可用于返回Folder对象:
public function rootFolder()
{
return $this->folders()->where("parentid", null)->first();
}