雄辩的更新模型模棱两可的行为

时间:2019-01-07 01:45:03

标签: eloquent laravel-5.2

我在更新个人资料/用户数据时遇到问题。我正在使用混合的模板方法\职责设计模式链来开始整个系统中的更新过程,以便更新过程在事务内开始,就好像发生了任何错误一样,都会回滚一切。一切正常,并且如果发生任何异常,一切都会回滚,但是,用户模型未更新,并且在登录时,由ORM发出的查询我发现在更新语句的where子句中未包含id列/值而它是针对个人资料模型的!这两个模型是相同的。我正在使用Laravel提供的User模型,该模型也从Model类间接扩展。我在每个模型中将primaryKey属性设置为id列名称,并且还将递增属性的默认值设置为true。

我尝试将增量设置为false,并使用更新属性传递id值,但是,它也无法正常工作。我正在尝试使用Google,但找不到答案...

class UserUpdateProcessor extends BaseProcessor
{
    private $repository;
    private $reqs;

public function __construct(BaseRepository $repo, $reqsArray)
{
    $this->repository = $repo;
    $this->reqs = $reqsArray;
}

public function Execute()
{
    $handler1 = new UpdateProfiler($this->repository);
    $handler2 = new UpdateAccount($this->repository->helperRepo);
    $handler1->nextHandler = $handler2;

    $handler1->process($this->reqs);
}
}

class UpdateProfiler extends Handler
{
public $nextHandler;
private $repository;
private $keys = [
    'id', 'user_login', 'phone_login', 'user_pass', 'user_email', 'notk'];

public function __construct(BaseRepository $repo)
{
    $this->repository = $repo;
}

public function process($reqsArray)
{
    $this->repository->update(array_diff_key($reqsArray, array_flip($this->keys)),
        $reqsArray[$this->repository->primaryKey]);

    if (!is_null($this->nextHandler) && $this->nextHandler instanceof Handler)
        $this->nextHandler->process($reqsArray);
}
}

class UpdateAccount extends Handler
{
public $nextHandler;
private $repository;
private $keys = [
    'id', 'user_login', 'phone_login', 'user_pass', 'user_email', 'notk'];

public function __construct(BaseRepository $repo)
{
    $this->repository = $repo;
}

public function process($reqsArray)
{
    $this->repository->update(array_intersect_key($reqsArray, array_flip($this->keys)),
        $reqsArray[$this->repository->primaryKey]);

    if (!is_null($this->nextHandler) && $this->nextHandler instanceof Handler)
        $this->nextHandler->process($reqsArray);
}
}

public function update(array $attributes, $id)
{
...
$model = $this->model->findOrFail($id);
$model->fill($attributes);
$model->save(); 
}

string(122) "update `wp_users` set `user_login` = ?, `user_pass` = ?, `user_email` = ?, `notk` = ?, `updated_at` = ? where `id` is null"
array(5) {
[0]=>
string(8) "wp_admin"
[1]=>
string(15) "wp_wordpress123"
[2]=>
string(31) "xyz@example.com"
[3]=>
string(16) "clut0tLDj4ESXftv"
[4]=>
string(19) "2019-01-07 00:55:04"
}

期望是在发送要更新的配置文件/用户数据时将其作为一个整体进行更新。我所拥有的是,仅当我记录由ORM生成的查询时才更新配置文件数据,我得到了上面的有线sql,试图更新具有空ID的用户

1 个答案:

答案 0 :(得分:0)

最后,我知道了。首先,我必须为数据库中的主键使用相同的大小写。我正在使用默认的Laravel提供的第二个问题是User模型和默认情况下定义为其中受保护的fillable属性。当您在模型对象上使用Eloquent填充方法然后保存时,fill方法将尝试访问fillable属性,如果它是public定义的,则将是不可能的!