2014-12-02 150 views
8

我想根据电子邮件不存在更新用户id,有没有一种方法做到这一点没有原始查询。Laravel更新查询

目前错误

{ “错误”:{ “类型”: “ErrorException”, “消息”: “从空 值创建缺省对象 ”, “文件”:“C :\ WAMP \ WWW \名人,吉姆\程序\ \控制器SignupController.php”, “线”:189}}

我的代码

public function changeAccountStatus ($plan, $userEmail){ 
     $UpdateDetails = User::where('email', '=', $userEmail)->first(); 
     $UpdateDetails->member_type = $plan; 
     $UpdateDetails->save(); 
    } 
+0

和'189'行有什么区别? – 2014-12-02 12:05:41

回答

5

此错误提示User::where('email', '=', $userEmail)->first()返回null,而不是更新模型时出现问题。

在尝试更改其属性或使用firstOrFail()方法之前,检查您是否确实拥有用户。

$UpdateDetails = User::where('email', $userEmail)->first(); 

if (is_null($UpdateDetails)) { 
    return false; 
} 

或使用firstOrFail()方法,世界上没有其他需要检查用户是否为null,因为这将引发异常(ModelNotFoundException)时没有找到一个模型,可以捕获使用App::error()http://laravel.com/docs/4.2/errors#handling-errors

$UpdateDetails = User::where('email', $userEmail)->firstOrFail(); 
4

你可以使用Laravel query builder,但这不是做的最佳途径。

检查Wader's answer below的Eloquent方式 - 这是更好的,因为它允许您检查实际上是否有用户匹配电子邮件地址,并处理错误,如果没有。

DB::table('users') 
     ->where('email', $userEmail) // find your user by their email 
     ->limit(1) // optional - to ensure only one record is updated. 
     ->update(array('member_type' => $plan)); // update the record in the DB. 

如果您有多个字段需要更新,您可以在结尾简单地向该数组添加更多值。

+0

我想你不明白这个问题。他希望在Eloquent find()方法中提供电子邮件,并希望它与emil列相匹配 – 2014-12-02 12:01:27

+0

我编辑了我的评论 – 2014-12-02 12:06:57

+0

为什么在op有一个Eloquent模型设置时使用查询生成器?问题不在于在Eloquent中不能轻松完成,但事实上在尝试设置对象的属性之前没有空的检查(请参阅我的回答) – Wader 2014-12-02 13:22:57

0

试着像这样做。

User::where('email', $userEmail)->update({'member_type' => $plan});