使用不同的表格在 laravel 4 上添加新项目

Add a new item on laravel 4 using different tables

这是我的物品模型。现在我想添加一个新项目,但出现此错误:SQLSTATE[23000]: Integrity constraint violation: 1048

<?php

class Items extends Eloquent
{

protected $guarded = [
    'id',
];

protected $fillable = [
    'name',
    'description',
    'price',
    'brand',


];

protected $table = 'items';

public function user()
{
    return $this->hasOne('User', 'user_ID', 'id');
}

public function size()
{
    return DB::table('sizes')->select('size')
        ->where('id', $this->size_ID)->first()->size;
}

public function color()
{
    return DB::table('colors')->select('color')
        ->where('id', $this->color_ID)->first()->color;
}

public function condition()
{
    return DB::table('conditions')->select('type')
        ->where('id', $this->condition_ID)->first()->type;
}

public function category()
{
    return DB::table('categories')->select('category')
        ->where('id', $this->category_ID)->first()->category;
}

public function images()
{
    return DB::table('images')->select('image')
        ->where('item_id', $this->id)->first()->image;
}

}

这是我的 post 保存项目的方法。

     public function store()
     {

     $item = new Items;
        $item->user_ID = Auth::id();
        $item->name = Input::get('name');
        $item->description = Input::get('description');
        $item->price = Input::get('price');
        $item->brand = Input::get('brand');
        $item->category = Input::get('Category');
        $item->condition = Input::get('Condition');
        $item->color = Input::get('Color');


        $item->save();


       }

这里是类别table的图片,条件和颜色table同理 http://imgur.com/9NCMYui

您正在创建 User 和 Item 之间的关系,但并未使用它。 您可以通过自己填写 id 来手动设置填充关系,但是您不会使用 Eloquent ORM 的强大功能。

我的建议是获取当前用户。 并像这样保存它。

$item->user()->save($user);

我建议 class 项目而不是项目的名称。 我发现它有更多的逻辑,大多数程序员也是如此。 table仍可称为物品