【问题标题】:Laravel 4 eloquent create doesn't work and fill doesLaravel 4 eloquent create 不起作用,而 fill 起作用
【发布时间】:2014-09-21 23:41:07
【问题描述】:

我想使用方法 create 以 Input::all() 作为参数创建一个名为 Property 的模型实例。输入仅包含可填写的字段。使用 create 方法时 laravel 会引发此异常:

alpha.ERROR: exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`propathai`.`properties`, CONSTRAINT `properties_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `properties` (`slug`, `updated_at`, `created_at`) values (, 2014-07-30 10:21:42, 2014-07-30 10:21:42))' in /home/ricardo/CHH/propathai/vendor/laravel/framework/src/Illuminate/Database/Connection.php:555

发生此异常是因为插入查询未填充所有输入参数。

{"bedrooms":"4","title":"ricardo","room_type":"apartment","type":"rent","furnished":"fully_furnished","aging":"new","user_id":"3"}

我尝试创建新的 Property 对象并使用 fill() 方法,它确实有效。

代码不工作

public function store()
{
    $input = Input::all();
    $input['user_id'] = Auth::user()->id;

    $property = Property::create($input);

    return Response::json(array('success' => true, 'redirect' => '/dashboard/properties/'.$property->id.'/edit-details'));
}

代码工作

public function store()
{
    $input = Input::all();
    $input['user_id'] = Auth::user()->id;

    $property = new Property;
    $property->fill($input);
    $property->save();

    return Response::json(array('success' => true, 'redirect' => '/dashboard/properties/'.$property->id.'/edit-details'));
}

型号

protected $guarded = array('id','services');

protected $fillable = array('user_id','bedrooms','title','room_type','type','furnished','aging');

如果有人知道为什么会这样,请告诉我。

谢谢。

【问题讨论】:

  • 你在使用外键吗??

标签: php laravel laravel-4 eloquent


【解决方案1】:

你的 slug 没有被填满。

 SQL: insert into `properties`
     (`slug`, `updated_at`, `created_at`) values (, 2014-07-30 10:21:42, 2014-07-30 10:21:42)

它可能是其中之一: 1-您的 slug 在您的输入表单上具有不同的名称属性。 2-它不在您的可填充数组上。 3- 它是空的、null 或被过滤。 例如:过滤我做的空输入:

$input = array_filter(Input::all(),'strlen');

顺便说一句,你这样做的方式并不是最好的方式。看一下这个: http://laravel.com/docs/eloquent 点击“一对多”

它在您的应用上会是什么样子? 您的模型用户

public function properties(){
    return $this->hasMany('Property');
}

你的模型属性

public function user(){
    return $this->belongsTo('User');
}

在您的控制器上:

$user = Auth::user();
$input = Input::all();
$input['user_id'] = $user->id;
$user->properties()->create($input);

这将是一种更“Laravel”的方法。

此外,如果您真的想成为专业人士,请观看 Jeffrey Way 的 Laracasts。 这是我在网上看到的最好的 Laravel4 在线资源。

【讨论】:

  • belongsToMany更改为belongsTo
  • Property 模型中可能是user() 的方法名称。
猜你喜欢
  • 2012-12-26
  • 2015-04-19
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
相关资源
最近更新 更多