【问题标题】:subcategory not showing on admin panel子类别未显示在管理面板上
【发布时间】:2019-10-16 19:01:35
【问题描述】:

我正在编辑一个 Laravel 4.3 站点,我有一个名为 categories 的数据库表,其中包含以下字段:

身份证 parent_id 姓名 我正在尝试在我的类别及其子类别视图中输出一个列表:

类别 另一个类别 子猫 子猫 子猫 我不太确定实现这一目标的最佳方法,希望有人能帮助我指出正确的方向:-)

这是我的控制器

公共函数存储(请求 $request) {

    $this->validate($request, [

        'name' =>'required'

    ]);




    $category= new Category;

    $category= Category::with('children')->whereNull('parent_id')->get();

    $category->name =$request->name;

    $category->save();}

【问题讨论】:

  • 您已经发布了存储类别的代码,请发布您尝试获取类别和子类别的代码。
  • 你确定这是对的吗? Category::with('children')->whereNull('parent_id')->get(),因为如果父母为空,孩子们将如何在那里?
  • 您要归档什么?您是否尝试存储类别并检索类别?

标签: laravel eloquent laravel-5.2


【解决方案1】:

希望对你有帮助

数据存储方法:

public function store(Request $request) {

    $this->validate($request, [
        'name' =>'required',
        'parent_id' => 'nullable|exists:category,id', //This will check the parent availability
    ]);


    $category= new Category;

    if ($request->has('parent_id')) {
        $category->parent_id =$request->parent_id;
    }

    $category->name =$request->name;
    $category->save();

    return $category;
}

获取所有数据的方法:

public function index() {
    $categories = Category::with('children')->all();

    return $categories;
}

通过id获取类别的方法:

public function categoryById(Category $category) {
    $category = Category::with('children')->where('id', $category->id)->first();

    return $category;
}

【讨论】:

  • 在返回dd($categories);之前尝试打印索引方法中的值
  • @user10945543 好的,如果它解决了您的问题,请将此答案标记为已接受并补充投票:)
  • 是的,当我添加子类别的类别时,它是在 parent_id 的帮助下创建的,但在我的索引中它显示为 1 home->1.1.-home1->1.2-home2 2 个人 3 联系人然后 (home 1 home 2) 再次在类别索引中重复并在我的本地主机中添加相同的内容,因为它应该显示在 home->home1 home2
  • 控制器公共函数 store(Request $request) { // dd($request->all()); $this->validate($request, [ 'name' =>'required', 'parent_id' => 'required|numeric', //这将检查父级的可用性如何顶级?其中 id 为 0?]) ;类别::create([ 'name'=>$request->name, 'parent_id'=>$request->parent_id ]); Session::flash('success', '类别创建成功');返回重定向()->返回(); }
  • create.blade.php--
猜你喜欢
  • 1970-01-01
  • 2019-02-12
  • 2019-09-21
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多