【问题标题】:Laravel multilevel menu doesn't workLaravel 多级菜单不起作用
【发布时间】:2018-07-09 20:03:02
【问题描述】:

我通过这个例子创建了多级菜单(第一次回复): How to create a database-driven multi-level navigation menu using Laravel

我总是得到空数组。这是我的数据库结构(数据库的名称也是“结构”)

structure_id 和 parent_id 是相关的。

这是我的代码:

App/navigation.php

<?php
namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;

class Navigation extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'structure';

    public function parent() {

        return $this->hasOne('structure', 'structure_id', 'parent_id');

    }

    public function children() {

        return $this->hasMany('structure', 'parent_id', 'structure_id');

    }

    public static function tree() {

        return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

    }

}

和控制器:

app/http/controllers/structurecontroller.php

<?php

namespace App\Http\Controllers\Superuser;

use App\Http\Controllers\Controller;
use App\Navigation;
use App\Structure as Model;

class StructureController extends Controller
{
    /**
     * Allow only for logged in
     * DashboardController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function index()
    {
        //$model = new Model();
        //$items = $model->getStructure();

        $items = Navigation::tree();
        var_dump($items);exit;



        return view('superuser.structure', ['items' => $items]);
    }
}

我很确定,我在数据库中有一些数据。那么,那里有什么问题呢?我总是从数据库中得到空数组。感谢帮助

【问题讨论】:

    标签: php laravel-5 drop-down-menu navigation


    【解决方案1】:

    这可能是您的数据库结构——您将 parent_id 声明为 NOT NULL,默认值为 0。然后在您的 tree 函数中执行以下操作:

    ...->where('parent_id', '=', NULL)->get(); 
    

    我猜“0”并没有像您预期的那样解析为 NULL。

    【讨论】:

      【解决方案2】:

      // 不要忘记添加 import: App\structure

      public function parent() {
          return $this->hasOne('App\structure', 'structure_id', 'parent_id');
      
      }
      

      【讨论】:

      • 欢迎您解释为什么需要'App\structure' 而不是原来的'structure'
      猜你喜欢
      • 2017-11-24
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      相关资源
      最近更新 更多