0

我正在做一个简单的添加产品和类别。类别有很多产品的地方。这是我的代码:

在创建类别表中:

Schema::create('categories', function($table){
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

在创建产品表中:

Schema::create('products', function($table){
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->string('title');
        $table->timestamps();
    });

在产品控制器中:

public function postCreate(){
    $validator = Validator::make(Input::all(), Product::$rules);
    if($validator->passes()){
        $product = new Product;
        $product->category_id = Input::get('category_id');
        $product->title = Input::get('title');
        $product->save();
        return Redirect::to('admin/products/index')
            ->with('message', 'Product Created');
    }
    return Redirect::to('admin/product/index')
        ->with('message', 'Something went wrong')
        ->withErrors($validator)
        ->withInput();
}

然后在我的 index.blade.php

{{ Form::open(array('url'=>'admin/products/create', 'files'=>true)) }}
    <p>
        {{ Form::label('category_id', 'Category') }}
        {{ Form::select('category_id', $categories) }}
    </p>
    <p>
        {{ Form::label('title') }}
        {{ Form::text('title') }}
    </p>
    {{ Form::submit('Create Product', array('class'=>'secondary-cart-btn')) }}
    {{ Form::close() }}

在我的路线中:

Route::controller('admin/categories', 'CategoriesController');
Route::controller('admin/products', 'ProductsController');

这里的问题是,如果类别表中没有项目/数据,则将显示产品页面,但我的选择框中当然没有数据,因为没有类别数据。但是如果我在 Category 表中放入一些数据,产品页面会显示错误“哎呀,好像出了点问题。”。我相信问题出在没有在类别表中获取数据的外键上。你们能帮我找出我的代码中的问题在哪里吗?以及如何使它工作。

这是在 app.php 打开调试后显示的内容

class ProductsController extends BaseController{
public function __construct() {
    $this->beforeFilter('csrf', array('on'=>'post'));
}
public function getIndex(){
    $categories = array();
    foreach (Category::all() as $category) {
        $categories[$category->id] = $categories->name;
    }
    return View::make('products.index')

ErrorException (E_NOTICE) 试图获取非对象的属性

Foreach 条件被突出显示。请告知此代码有什么问题。

4

0 回答 0