php - 添加子类别 - Laravel 5.2

标签 php mysql laravel laravel-5

我需要将子类别插入到我的主类别中。我已经完成了显示、添加、编辑和删除父类别的所有工作。但现在我一直在思考如何将子类别实际添加到我的父类别之一。

以下是类别和子类别的表格。

Categories Table

如您所见,我已经在 iPhone 下有一个子类别,这是我通过数据库手动添加的。要将子类别添加到主类别,我只需单击 + 子类别链接即可进入添加子类别的表单。

这是我显示和添加子类别的路线:

Route::group(["middleware" => 'admin'], function(){

    /** More category routes here -->, just hidden for shortness **/


    /** Show the Admin Add Sub-Categories Page **/
    Route::get('admin/categories/addsub/{id}', [
        'uses' => '\App\Http\Controllers\CategoriesController@addSubCategories',
        'as'   => 'admin.category.addsub',
        'middleware' => ['auth'],
    ]);


    /** Post the Sub-Category Route **/
    Route::post('admin/categories/postsub/{id}', [
        'uses' => '\App\Http\Controllers\CategoriesController@addPostSubCategories',
        'as'   => 'admin.category.postsub',
        'middleware' => ['auth'],
    ]);


});

这是我的 CategoryController.php:

它被缩短只是为了显示子类别功能。这就是我在向父类别添加子类别时遇到问题的地方

class CategoriesController extends Controller
    /**
     * Return the view for add new sub category
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function addSubCategories($id) {

        $category = Category::findOrFail($id);

        return view('admin.category.addsub', compact('category'));
    }


    /**
     * @param $id
     * @param CategoryRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addPostSubCategories($id, CategoryRequest $request) {

        // Find the Parent Category ID
        $category = Category::findOrFail($id);

        // Insert into categories where the Parent_id = to the category ID
        $categories = Category::where('parent_id', '=', $category);


        // Assign $category to the Category Model, and request all validation rules
        $categories = new Category($request->all());

        // Then save the newly created category in DB
        $categories->save();

        // Flash a success message
        flash()->success('Success', 'Sub Category added successfully!');

        // Redirect back to Show all categories page.
        return redirect()->route('admin.category.show');
    }

}

我的 Category.php 模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    protected $table = 'categories';

    protected $fillable = ['name'];

    protected $guarded = ['id'];


    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }



    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

}

我的添加子类别表单:

 <form role="form" method="POST" action="{{ route('admin.category.postsub', $category->id) }}">
                    {{ csrf_field() }}
                    <li class="collection-item blue">
                        <h5 class="white-text text-center">
                            Sub-Category to {{ $category->name }}
                        </h5>
                    </li>
                    <li class="collection-item">
                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                      <input type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Add Sub-Category">
                            @if($errors->has('name'))
                                <span class="help-block">{{ $errors->first('name') }}</span>
                            @endif
                        </div>
                    </li>
                    <li class="collection-item blue">
                        <div class="form-group text-center">
                            <button type="submit" class="btn btn-link grey lighten-5">Create Sub-Category</button>
                        </div>
                    </li>
                </form>

我的数据库结构:

My DB structure

我特别需要类别 Controller 中的 addPostSubCategories() 函数的帮助,因为现在如果我添加一个新的子类别,它只会添加一个新的父类别,而不是子类别

最佳答案

访问此处查看详细说明:https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

这就是您想要的:

/**
 * @param $id
 * @param CategoryRequest $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function addPostSubCategories($id, CategoryRequest $request) {

    // Find the Parent Category
    $category = Category::findOrFail($id);

    // Create the new Subcategory
    $subcategory = new Category($request->all());

    // Save the new subcategory into the relationship
    $category->children()->save($subcategory);

    // Flash a success message
    flash()->success('Success', 'Sub Category added successfully!');

    // Redirect back to Show all categories page.
    return redirect()->route('admin.category.show');
}

关于php - 添加子类别 - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36388326/

相关文章:

php - 如何使 PHP 进行此查询

php - 拉拉维尔 5.3 : Cannot add Additional user info for User registration

php - Android/PHP - 通过网络服务器发送 txt 文件?

php - 拉拉维尔 : Issue in database connection when use # keyword in env file

php - 如何按两列对 MySQL 查询进行排序

mysql - 显示具有多个类别的值的一行

列更新时的Mysql死锁

php - Laravel-livewire:为什么触发事件会执行 render() 方法?

php - Laravel - 如何获得特定用户的委托(delegate)角色

php - ereg_replace 到 preg_replace?