简体   繁体   English

PHP:Slim Framework / Eloquent ORM质量分配错误

[英]PHP: Slim Framework/Eloquent ORM mass assignment error

I am using eloquent with slim framework outside of laravel, I have controllers that help perform CRUD operations. 我在laravel之外使用简洁的框架,我有控制器,可以帮助执行CRUD操作。 When I try to perform mass assignment operation Eloquent throws an error saying: 当我尝试执行质量赋值操作时,Eloquent会抛出错误说:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed:
 emoji.name (SQL: insert into "emoji" ("user_id", "updated_at", "created_at") 
values (1, 2016-01-02 02:56:43, 2016-01-02 02:56:43))

Bellow is my controller and Model: 贝娄是我的控制者和型号:

public function create(ServerRequestInterface $request, ResponseInterface $response)
{
    $data   =   $request->getParsedBody();
    $uid    =   $data['uid'];
    $keywords   =   $data['keywords'];

    $body   =   $response->getBody();

        $user   =   User::find($uid);
        $user->emojis()->create([
            'name'  =>  $data['name'],
            'char'  =>  $data['char'],
            'category'  =>  $data['category'],
        ]);
//            $emoji = new Emoji();
//            $emoji->name  =  $data['name'];
//            $emoji->char  =  $data['char'];
//            $emoji->category  =  $data['category'];
//            $emoji->save();
        return $response;
    }

The application works when I use the lines that are commented above, but not the other: 当我使用上面注释的行而不是另一行时,应用程序可以正常工作:

My model is below: 我的模型如下:

namespace BB8\Emoji\Models;
use BB8\Emoji\Models\BaseModel;

class Emoji  extends BaseModel
{
    protected $table    = 'emoji';
    protected $dates    = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = array('name', 'char', 'category', 'created_at', 'updated_at', 'user_id');

public function user()
{
    return $this->belongsTo("BB8\Emoji\Models\User");
}

public function keywords()
{
    return $this->hasMany("BB8\Emoji\Models\EmojiKeyword");
}
}

When I var_dump($data) I get the below: 当我var_dump($data)我得到以下内容:

array (size=6)
  'name' => string 'Happy Face' (length=10)
  'char' => string ')' (length=1)
  'keywords' => 
    array (size=1)
      0 => string 'happy' (length=5)
  'category' => string 'Happy' (length=5)
  'created_by' => int 1
  'uid' => int 1

Below is my UserModel 下面是我的UserModel

namespace BB8\Emoji\Models;
use BB8\Emoji\Models\BaseModel;
class User extends BaseModel
{
public $timestamps = false;
protected $fillable = ['username', 'password', 'jit'];

public function emojis()
{
    return $this->hasMany('BB8\Emoji\Models\Emoji');
}

public static function auth($username, $password)
{
    $user       =   static::where('username', '=', $username)->first();

    if (isset($user->exists) && $user->exists) {
        if (strcmp(hash('sha256', $password), $user->password) == 0) {
            return $user;
        }
    }

    return false;
}



  public static function isAuthenticated($token)
    {
    }
  }

BaseModel.php : BaseModel.php:

 namespace BB8\Emoji\Models;
use BB8\Emoji\Database\Connection;

class BaseModel extends \Illuminate\Database\Eloquent\Model
{
    public function __construct()
    {
        $dotenv = new \Dotenv\Dotenv(__DIR__.'/../../');
        $dotenv->load();
    }
}

I have multi-triple checked my code without seeing what is wrong, yet it throws the constraint violation error. 我有多重三重检查我的代码,但没有看到什么是错误,但它抛出约束违规错误。 Is this a bug with eloquent or am I doing something wrong. 这是一个雄辩的错误还是我做错了什么。

Looks like your BaseModel is the problem. 看起来你的BaseModel是个问题。 Try changing your constuctor to this: 尝试将您的构造更改为:

public function __construct(array $attributes = [])
{
    $dotenv = new \Dotenv\Dotenv(__DIR__.'/../../');
    $dotenv->load();

    parent::__construct($attributes);
}

Explanation: 说明:

Here is Laravel's original model's constructor. 这是Laravel的原始模型的构造函数。

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

It accepts an array of attributes and does a few things with it, but keep the fill method in mind. 它接受一系列属性并用它做一些事情,但要记住fill方法。

Now, here is what you are doing to create your emoji: 现在,您正在做的是创建表情符号:

$user->emojis()->create([
    'name'  =>  $data['name'],
    'char'  =>  $data['char'],
    'category'  =>  $data['category'],
]);

This calls the HasMany class' create method. 这将调用HasMany类的create方法。 I removed all but the line of code you want to focus on: 除了你想要关注的代码行之外,我删除了所有代码:

public function create(array $attributes)
{
    ...

    $instance = $this->related->newInstance($attributes);

    ...
}

This basically creates a new instance of your model and passing in the array of attributes. 这基本上创建了模型的新实例并传入属性数组。 Essentially something like this: 基本上是这样的:

new Emoji([
    'name'  =>  $data['name'],
    'char'  =>  $data['char'],
    'category'  =>  $data['category'],
]);

However, your constructor is not accepting an array of attributes like Laravel's models and that changes the actual behavior of models. 但是,构造函数不接受像Laravel模型这样的属性数组,并且会更改模型的实际行为。 The values are not being filled. 这些值未被填充。 The solution at the top should fix your problem. 顶部的解决方案应该可以解决您的问题。 After you load the environment variables, it just defers back to Laravel's default behavior. 加载环境变量后,它只会延迟回到Laravel的默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM