简体   繁体   English

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

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

When updating my Post model, I run:更新我的Post model 时,我运行:

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

$post->save();

This does not update my post.不会更新我的帖子。 But it should according to the Laravel docs on updating Eloquent models .但它应该根据Laravel 文档更新 Eloquent 模型 Why is my model not being updated?为什么我的 model 没有更新?

Post model: Post model:

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

   ....
}

Post controller: Post controller:

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 $fetchedPost is the same post as before without the updated data.向我显示$fetchedPost与之前的帖子相同,但没有更新数据。

Check your database table if the 'id' column is in uppercase 'ID'.如果“id”列是大写“ID”,请检查您的数据库表。 Changing it to lower case allowed my save() method to work.将其更改为小写允许我的 save() 方法工作。

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。

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);

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

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('/');
}

Running dd() inside a DB::transaction will cause a rollback, and the data in database will not change.DB::transaction中运行dd()将导致回滚,并且数据库中的数据不会改变。

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”的行为自然会导致脚本停止,因此不会更改数据库。

Check your table if primary key is not id ("column name should be in small letters only") if you have set column name with different key then put code in your Model like this如果主键不是 id(“列名只能是小写字母”),请检查您的表如果您使用不同的键设置了列名,然后将代码像这样放在您的模型中

protected $primaryKey   = 'Id';

So this might be one of the possible solution in your case also if your column name contains capital letters.因此,如果您的列名包含大写字母,这也可能是您的情况的可能解决方案之一。 Yes this worked for me fine, You should have column names in small letter, If you don't have then mention it in the model file, mainly for primaryKey by which your model will try to access database.是的,这对我来说很好,你应该有小写字母的列名,如果你没有然后在模型文件中提到它,主要是你的模型将尝试访问数据库的 primaryKey。

For use save () method to update or delete if the database has a primary key other than "id".如果数据库的主键不是“id”,则使用save()方法更新删除 need to declare the attribute primaryKey = "" in the model, it will work需要在模型中声明属性primaryKey = "",才会生效

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('/');
}

In my experience, if you select an Eloquent model from the db and the primary_key column 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 id is the primary_key defined on the target table.因此,与其做\App\Users::where(...)->first(['email']) ,不如做\App\Users::where(...)->first(['id','email']) ,其中id是在目标表上定义的primary_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_key column since all the columns will be fetched.如果通过仅检索几列实现的(有时是微优化)对您来说并不重要,您可以通过执行\App\Users::where(...)->first()来获取所有列,在在这种情况下,您无需担心primary_key列的名称,因为将获取所有列。

If you using transactions.如果您使用交易。 Do not forget call DB::commit();不要忘记调用DB::commit();

It must look like this:它必须如下所示:

try{
    DB::beginTransaction();
    // Model changes
    $model->save();
    DB::commit();
}catch (\PDOException $e) {
    DB::rollBack();
}

I have the same issue although there are try / catch block in controller@action() but there were no response, it just stops at $model->save();我有同样的问题,虽然在controller@action()中有try / catch块但是没有响应,它只是停止在$model->save(); there is no log entry either in apache error.log or laravel.log . apache error.loglaravel.log中没有日志条目。 I have just wrapped the save() with try / cactch as follows, that helped me to figure out the issue我刚刚用try / cactch包装了save()如下,这帮助我找出了问题

    try{
        $model->save();
    }
    catch (\PDOException $e) {
        echo $e->getMessage();
    }

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.php template.我发现我无法在home.blade.php模板上名为{{ generateUrl() }}的函数中save()我的模型。 What worked was moving the save() call to the controller that return s the home.blade.php template.起作用的是将save()调用移动到return home.blade.php模板的控制器。 (IE, save() ing before the view is return ed, then only performing read operations within {{ generateUrl() }} .) (IE,在视图return之前save() ing,然后只在{{ generateUrl() }}内执行读取操作。)

I was (and am) generating a state to 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 User from the database, but it was unable to save() it back.这能够从数据库中find() User ,但无法将其save()回来。 No errors were produced.没有产生错误。 The function appeared to work properly... until I tried to read the User 's state later, and found that it did not match the state in the URL.该功能似乎可以正常工作......直到我稍后尝试读取Userstate ,发现它与 URL 中的state不匹配。

Here is what did work.这是起作用的。

Instead of trying to save() my User as the page was being assembled, I generated the state , save() d it, then rendered the page:在组装页面时,我没有尝试save()我的User ,而是生成了statesave() d 它,然后呈现页面:

// routes/web.php

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

Landing at the root directory sends you to the index() function of HomeController.php :登陆根目录会将您带到HomeController.phpindex()函数:

// 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()模型,而不是在页面组装期间。

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

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