php Laravel Eloquent $model->save() 不保存但没有错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46919857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:16:06  来源:igfitidea点击:

Laravel Eloquent $model->save() not saving but no error

phplaravellaravel-5eloquentlaravel-5.5

提问by Jacob

When updating my Postmodel, I run:

更新Post模型时,我运行:

$post->title = request('title');
$post->body = request('body');

$post->save();

This does notupdate my post. But it should according to the Laravel docs on updating Eloquent models. Why is my model not being updated?

这并没有更新我的职务。但它应该根据更新 Eloquent 模型的 Laravel 文档为什么我的模型没有更新?

Postmodel:

Post模型:

class Post extends Model
{
    protected $fillable = [
        'type',
        'title',
        'body',
        'user_id',
    ];

   ....
}

Postcontroller:

Post控制器:

public function store($id)
{
    $post = Post::findOrFail($id);

    // Request validation
    if ($post->type == 1) {
        // Post type has title
        $this->validate(request(), [
            'title' => 'required|min:15',
            'body' => 'required|min:19',
        ]);

        $post->title = request('title');
        $post->body = request('body');
    } else {
        $this->validate(request(), [
            'body' => 'required|min:19',
        ]);

        $post->body = request('body');
    }

    $post->save();

    return redirect('/');
}

Bonus info

奖金信息

Running dd($post->save())returns true.

运行dd($post->save())返回true

Running

跑步

$post->save();

$fetchedPost = Post::find($post->id);
dd($fetchedPost);

shows me that $fetchedPostis the same post as before withoutthe updated data.

向我展示$fetchedPost了与之前没有更新数据的帖子相同的帖子。

回答by Asuquo Bartholomew Ikechukwu

Check your database table if the 'id' column is in uppercase 'ID'. Changing it to lower case allowed my save() method to work.

如果“id”列是大写的“ID”,请检查您的数据库表。将其更改为小写允许我的 save() 方法工作。

回答by Mark Walker

I had the same and turned out to be because I was filtering the output columns without the primary key.

我有同样的结果,因为我正在过滤没有主键的输出列。

$rows = MyModel::where('...')->select('col2', 'col3')->get();
foreach($rows as $row){
    $rows->viewed = 1;
    $rows->save();
}

Fixed with

固定与

$rows = MyModel::where('...')->select('primary_key', 'col2', 'col3')->get();

Makes perfect sense on review, without the primary key available the update command will be on Null.

在时非常有意义,如果没有可用的主键,更新命令将为 Null。

回答by Moeen Basra

Since Laravel 5.5 laravel have change some validation mechanism I guess you need to try this way.

由于 Laravel 5.5 laravel 更改了一些验证机制,我想您需要尝试这种方式。

public function store(Request $request, $id)
{
    $post = Post::findOrFail($id);

    $validatedData = [];

    // Request validation
    if ($post->type == 1) {
        // Post type has title
        $validatedData = $request->validate([
          'title' => 'required|min:15',
          'body' => 'required|min:19',
      ]);
    } else {
      $validatedData = $request->validate([
        'body' => 'required|min:19',
    ]);
    }

    $post->update($validatedData);

    return redirect('/');
}

回答by Bardiya B.

I had the same problem and changing the way I fetch the model solved it!

我有同样的问题,改变我获取模型的方式解决了它!

Was not saving even though everything was supposedly working just as you have mentioned:

即使一切都按照您提到的那样工作,也没有保存:

$user = User::find($id)->first(); 

This is working:

这是有效的:

$user = User::find($id);

回答by Vampire

You have to make sure that the instance that you are calling save()on has the attribute id

您必须确保您正在调用的实例save()具有该属性id

回答by MalemScha

Try this

尝试这个

public function store($id,Request $request)
{
    $post = Post::findOrFail($id);

    // Request validation
    if ($post->type == 1) {
        // Post type has title
         $request->validate([
            'title' => 'required|min:15',
            'body' => 'required|min:19',
        ]);
        $post->update([
              'title' => request('title');
              'body' => request('body');
             ]);
    } else {
         $request->validate([
            'body' => 'required|min:19',
        ]);

        $post->update([
              'body' => request('body');
             ]);
    }

    return redirect('/');
}

回答by Damilola Olowookere

In my experience, if you select an Eloquent model from the db and the primary_keycolumn is not part of the fetched columns, your $model->save()will return true but nothing is persisted to the database.

根据我的经验,如果您从数据库中选择一个 Eloquent 模型并且该primary_key列不是提取列的一部分,您$model->save()将返回 true 但没有任何内容被持久化到数据库中。

So, instead of doing \App\Users::where(...)->first(['email']), rather do \App\Users::where(...)->first(['id','email']), where idis the primary_keydefined on the target table.

所以,与其做\App\Users::where(...)->first(['email']),而做的\App\Users::where(...)->first(['id','email']),在这里idprimary_key对目标表定义。

If the (sometimes micro-optimization) achieved by retrieving only a few columns is not really of importance to you, you can just fetch all columns by doing \App\Users::where(...)->first(), in which case you do not need to bother about the name of the primary_keycolumn since all the columns will be fetched.

如果通过仅检索几列实现的(有时是微优化)对您来说并不重要,您可以通过执行 获取所有列\App\Users::where(...)->first(),在这种情况下,您无需担心primary_key列的名称,因为所有将获取列。

回答by ??????-GEXAYR

Running dd()inside a DB::transactionwill cause a rollback, and the data in database will not change.

dd()在a里面运行DB::transaction会导致回滚,数据库中的数据不会发生变化。

The reason being, that transaction will only save the changes to the database at the very end. Ergo, the act of running "dump and die" will naturally cause the script to cease and no therefore no database changes.

原因是,该事务只会在最后保存对数据库的更改。因此,运行“dump and die”的行为自然会导致脚本停止,因此不会更改数据库。

回答by Cameron Hudson

I have been experiencing the same issue and found a workaround. I found that I was unable to save()my model within a function called {{ generateUrl() }}on my home.blade.phptemplate. What worked was moving the save()call to the controller that returns the home.blade.phptemplate. (IE, save()ing before the view is returned, then only performing read operations within {{ generateUrl() }}.)

我遇到了同样的问题并找到了解决方法。我发现我无法在模板上save()调用的函数中{{ generateUrl() }}使用我的home.blade.php模型。有效的是将save()调用移动到return作为home.blade.php模板的控制器。(IE,save()在视图被return编辑之前 ing ,然后只在{{ generateUrl() }}.内执行读取操作。)

I was (and am) generating a stateto put in a URL on page load:

我曾经(并且正在)生成一个state在页面加载时放入一个 URL:

<!--views/home.blade.php-->

<a href="{{ EveAuth::generateUrl() }}">Add Character</a>

Below is what did not work.

以下是不起作用的内容。

// Providers/EveAuth.php

function generateUrl()
{
    $authedUser = auth()->user();
    if (!$authedUser) {
        return "#";
    }
    $user = User::find($authedUser->id);
    $user->state = str_random(16);
    $user->save();

    $baseUrl = 'https://login.eveonline.com/oauth/authorize?state=';

    return $baseUrl . $user->state;
}

This was able to find()the Userfrom the database, but it was unable to save()it back. No errors were produced. The function appeared to work properly... until I tried to read the User's statelater, and found that it did not match the statein the URL.

这是能够find()User从数据库中,但它无法save()回来。没有产生错误。该函数似乎工作正常...直到我稍后尝试阅读User' state,发现它state与 URL 中的不匹配。

Here is what did work.

这是有效的方法。

Instead of trying to save()my Useras the page was being assembled, I generated the state, save()d it, then rendered the page:

save()我没有User在页面组装时尝试我,而是生成了state, save()d 它,然后呈现页面:

// routes/web.php

Route::get('/', 'HomeController@index');

Landing at the root directory sends you to the index()function of HomeController.php:

登陆根目录会带你到以下index()功能HomeController.php

// Controllers/HomeController.php

public function index()
{
    $authedUser = auth()->user();
    if ($authedUser) {
        $user = User::find($authedUser->id);
        $user->state = str_random(16);
        $user->save();
    }
    return view('home');
}

Then, when generating the URL, I did not have to save()the User, only read from it:

然后,生成的URL时,我没得save()User,只是从它读:

// Providers/EveAuth.php

function generateUrl()
{
    $authedUser = auth()->user();
    $user = User::find($authedUser->id);

    $baseUrl = 'https://login.eveonline.com/oauth/authorize?state=';

    return $baseUrl . $user->state;
}

This worked! The only difference (as far as I see) is that I'm save()ing the model before page assembly begins, as opposed to during page assembly.

这有效!唯一的区别(据我所知)是我save()在页面组装开始之前对模型进行了建模,而不是在页面组装期间。