Eloquent firstOrNew()查询无法识别传递给它的参数

时间:2016-07-14 18:02:23

标签: php laravel eloquent

我正在尝试使用随机字符串名称创建一组虚假用户,稍后我将使用这些名称。我遇到了一个错误,它没有识别我通过的一些变量。以下是我的代码:

        $password = bcrypt($this->generateRandomString(15));

        $user = User::firstOrNew([
            'email' => ($firstName . '@company.com'),
            'password' => $password,
            'username' => $username,
            'firstname' => $firstName,
            'lastname' => $lastName,
        ]);
        $user->save();
        $userIds[] = $user->id;

我正在使用firstOrNew以防万一已经输入了具有该随机用户名的用户,在这种情况下我只会使用其ID。

我知道$username$firstName$lastName都通过测试在这些对象中都有数据,但无论出于何种原因,我都会在{{1}上收到有关重复错误的错误因为它认为字段是空的(''),即使我知道我的变量不是。

换句话说,SQL语句只传递电子邮件和密码,而不传递其他三个变量。有什么想法吗?

错误讯息:

'username'

2 个答案:

答案 0 :(得分:2)

好的,所以基于错误(发布您的原始错误)...看起来您没有传递以下值,'username' => $username, 'firstname' => $firstName, 'lastname' => $lastName, ...

请确保在User模型中,fillable下有protected $fillable = [ ... 'username', 'firstname', 'lastname', ]; ,如下所示:

timeOut = [NSTimer scheduledTimerWithTimeInterval:25 target:self selector:@selector(timeOutMethod) userInfo:nil repeats:NO];

-(void) timeOutMethod{

    [self performSelector:@selector(loadSlideshowView)
               withObject:nil
               afterDelay:5];

}

-(void) loadSlideshowView{


    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SlideShowViewController *myVC = (SlideShowViewController *)[storyboard instantiateViewControllerWithIdentifier:@"slideShowImages"];
    [self presentViewController:myVC animated:YES completion:nil];

}

我认为这是你的问题所在。

答案 1 :(得分:1)

方法firstOrNew()正在尝试使用所有给定的列/值对定位数据库记录。您应该只使用创建唯一键的属性,例如电子邮件。

然后,如果模型是新的(exists为false),您将需要检查模型的exists属性以填充其余字段并保存。

相关问题