我的项目是在Laravel 5.5中 我将表格 wposts 用于laravel中的多级菜单和同时发布的帖子。表格的字段是:
- id
- parentpost (id of parent post)
- title
- porder (order of posts in the same menu)
在Controller中我有函数 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;
}
在之后的同一个Controller中,我有一个名为预览的功能,可以呈现视图
public function preview($templ){
$pwposts = \App\Wpost::with('parent')->get();
$pwposts= $this->getwposts(0,[]);
dd($pwposts);
return view('templates.$templ1,compact('pwposts'));
}
我快到了。 tabble的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');
}
}
我堆积如山。你能帮助我吗? 提前谢谢
答案 0 :(得分:0)
您可以尝试https://github.com/etrepat/baum
我用过,我感觉很好
答案 1 :(得分:0)
在您的模型中添加$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');
}
}
现在,如果您想以递归方式获取孩子,可以使用。
$pwposts = \App\Wpost::with('children')->get();
希望这有帮助
答案 2 :(得分:0)
尝试一下:
| id | parend_id | name | url |
| 1 | 0 | Level 1 | /level_one |
| 2 | 1 | Sublevel | /level_one/sublevel |
| 3 | 0 | Level 2 | /level_two |
型号
public function children() {
return $this->hasMany('App\Menus', 'parent_id', 'id');
}
public static function tree() {
return static::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', '0')->get();
}
控制器
$components = new Component;
try {
$menu = $components->tree();
} catch (Exception $e) {}
return response()->json($menu);