【问题标题】:Add a new item on laravel 4 using different tables使用不同的表在 laravel 4 上添加一个新项目
【发布时间】:2015-08-22 19:51:12
【问题描述】:

这是我的物品模型。现在我想添加一个新项目,但出现此错误: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;
}

}

这是我保存物品的发布方法。

     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();


       }

这是一张类别表的图片,条件和颜色表的逻辑是一样的。 http://imgur.com/9NCMYui

【问题讨论】:

    标签: php laravel-4 add


    【解决方案1】:

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

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

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

    我建议使用类 Item 而不是 Items 的名称。 我发现它有更多的逻辑,大多数程序员也是如此。 该表仍然可以称为项目。

    【讨论】:

    • 感谢您的回答!我在问题中的解释不是很聪明。如图所示,我有一个类别表。我的想法是这样的:当用户在新项目上输入技术类别时,项目表 category_id 将为 1。条件和颜色相同!我真的不知道该怎么做,因为我也是 laravel 和 php 的初学者。
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2013-03-25
    • 2019-09-27
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    相关资源
    最近更新 更多