【发布时间】:2018-08-28 05:40:58
【问题描述】:
我的项目在 Laravel 5.5 中 我有一张 wposts 表格,用于 laravel 中的多级菜单和同时发布的帖子。该表的字段为:
- id
- parentpost (id of parent post)
- title
- porder (order of posts in the same menu)
在控制器中,我具有 getwposts 功能,可以使用递归获取帖子,从而获得多级菜单。
private function getwposts($parentid = 0,$wposts = []){
foreach(Wpost::where('parentpost', $parentid)->orderby('porder')->get() as $pwpost)
{
echo $pwpost->id.'-' ;
$wposts[$pwpost->id] = $this->getwposts($pwpost->id,$wposts);
}
return $wposts;
}
在那之后,在同一个控制器中,我有一个名为 preview 的函数来呈现视图
public function preview($templ){
$pwposts = \App\Wpost::with('parent')->get();
$pwposts= $this->getwposts(0,[]);
dd($pwposts);
return view('templates.$templ1,compact('pwposts'));
}
我快到了。表格的莱特顺序是
但结果是
虽然使用 echo 我在树视图中看到了正确的记录顺序,但还是不行。 我的模型是
namespace App;
use Illuminate\Database\Eloquent\Model;
class Wpost extends Model
{
protected $fillable =
['parentpost','title','body','author','storeid','porder','haskids'];
protected $table = 'wposts';
public function children(){
return $this->hasmany(Wpost::class, 'parentpost');
}
public function parent(){
return $this->belongsTo(Wpost::class, 'parentpost');
}
}
我被堆叠了。你能帮助我吗? 提前谢谢
【问题讨论】:
-
也发布你的型号代码。
-
我也编辑并发布了我的模型。
标签: php laravel recursion menu