Php 具有递归函数的laravel中的多级菜单
我的项目是在拉雷维尔5.5 我有一个表wposts,用于同时在laravel和posts中创建多级菜单。该表的字段包括:Php 具有递归函数的laravel中的多级菜单,php,laravel,recursion,menu,Php,Laravel,Recursion,Menu,我的项目是在拉雷维尔5.5 我有一个表wposts,用于同时在laravel和posts中创建多级菜单。该表的字段包括: - id - parentpost (id of parent post) - title - porder (order of posts in the same menu) 在控制器中,我有一个函数getwposts,它使用递归来获取文章,从而拥有一个多级菜单 private function getwposts($parentid = 0,$wposts = []){
- 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;
}
在之后的同一个控制器中,我有一个名为“预览”的函数,用于渲染视图
public function preview($templ){
$pwposts = \App\Wpost::with('parent')->get();
$pwposts= $this->getwposts(0,[]);
dd($pwposts);
return view('templates.$templ1,compact('pwposts'));
}
我快到了。table的wright顺序是
但结果是
虽然使用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');
}
}
我累坏了。你能帮助我吗?
提前感谢您可以试试
我用过,我感觉很好在你的模型中添加
$with=['children']
namespace App;
use Illuminate\Database\Eloquent\Model;
class Wpost extends Model
{
protected $fillable =
['parentpost','title','body','author','storeid','porder','haskids'];
protected $table = 'wposts';
protected $with = ['children'];
public function children(){
return $this->hasmany(Wpost::class, 'parentpost');
}
public function parent(){
return $this->belongsTo(Wpost::class, 'parentpost');
}
}
现在,如果您想以递归方式获取child,可以使用
$pwposts = \App\Wpost::with('children')->get();
希望这有帮助试试这个:
| id | parend_id | name | url |
| 1 | 0 | Level 1 | /level_one |
| 2 | 1 | Sublevel | /level_one/sublevel |
| 3 | 0 | Level 2 | /level_two |
模型
控制器
$components = new Component;
try {
$menu = $components->tree();
} catch (Exception $e) {}
return response()->json($menu);
也可能重复发布你的模型代码。我也编辑并发布了我的模型。这里面有很多理论,我没有时间去测试它。谢谢,我不明白附加的意思。我可以在我在模型中定义关系的语法中使用-with-,但它不会改变任何东西。`$pwposts=\App\Wpost::with('children')->get();`此行将以递归方式返回表中的所有数据
$with=['children']
将返回每个请求中的子项,我在getwposts函数中添加了-with-,并变成如下foreach(Wpost::with('children')->where('parentpost',$parentid)->where('storeid',$id)->orderby('porder')->get()as$pwspost)$with=['children代码>您是否在模型中使用了此选项?
$components = new Component;
try {
$menu = $components->tree();
} catch (Exception $e) {}
return response()->json($menu);