my project is in Laravel 5.5 i have the table wposts for a multilevel menu in laravel and posts in the same time. The fields of the table are:
- id
- parentpost (id of parent post)
- title
- porder (order of posts in the same menu)
In the Controller i have the function getwposts to get the posts using recursion to have a multilevel menu.
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;
}
In the same Controller after that, i have a function called preview that renders the view
public function preview($templ){
$pwposts = \App\Wpost::with('parent')->get();
$pwposts= $this->getwposts(0,[]);
dd($pwposts);
return view('templates.$templ1,compact('pwposts'));
}
I am almost there. The wright order of the tabble is
but the results are
Although with echo i see the correct order of the records in the tree view there isn't ok. My model is
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');
}
}
I am stacked. Can you help me? thanks in advance
You can try https://github.com/etrepat/baum
I used, i feel so good
In your Model add $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');
}
}
Now if you want to get the childs in a recursive way you can use.
$pwposts = \App\Wpost::with('children')->get();
Hope this helps
Try this:
| id | parend_id | name | url |
| 1 | 0 | Level 1 | /level_one |
| 2 | 1 | Sublevel | /level_one/sublevel |
| 3 | 0 | Level 2 | /level_two |
Model
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();
}
Controller
$components = new Component;
try {
$menu = $components->tree();
} catch (Exception $e) {}
return response()->json($menu);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.