【发布时间】: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