[英]Laravel 4 eloquent create doesn't work and fill does
我想使用Input :: all()作為參數,使用create方法創建一個名為Property的模型實例。 輸入僅包含可填寫的字段。 當使用創建方法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');
如果有人知道為什么會發生,請告訴我。
謝謝。
你的沒有被填補。
SQL: insert into `properties`
(`slug`, `updated_at`, `created_at`) values (, 2014-07-30 10:21:42, 2014-07-30 10:21:42)
可能是其中之一:1-您的子彈在輸入表單上具有不同的名稱屬性。 2-它不在您的可填充數組上。 3-它可以為空,為空或被過濾。 例如:過濾空的輸入,我這樣做:
$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);
那將是一種更“拉威爾”的方法。
另外,如果您真的想觀看Jeffrey Way的PRO觀看Laracasts。 這是我在網上看到的Laravel4的最佳在線資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.