【问题标题】:laravel - update the model(!) without selecting firstlaravel - 更新模型(!)而不先选择
【发布时间】:2020-01-02 06:35:35
【问题描述】:

我有以下ResearchModel(雄辩):

$research = new ResearchModel();
$research->id = 2;
$research->name = "test";
$research->save();

我希望 Laravel 运行 update 语句(因为我设置了 id),但它运行的是插入语句。

$research->update(); 不会做任何事情。

我不想在这种情况下使用array,因为我需要触发雄辩的模型事件。

我也不想在之前运行ResearchModel::find(2);,这会在我的用例中导致严重的性能问题。

有什么方法可以通过id 告诉 Laravel 更新吗? 谢谢

【问题讨论】:

    标签: laravel model


    【解决方案1】:

    如果您不想先“选择”。然后就可以直接更新了。这将只运行一个查询。

    $research = ResearchModel::where('id',2)->update([
        'name' => 'test',
    ]);
    

    【讨论】:

    • 这个选项会触发模型事件吗?另外,这将首先运行查询,还是仅更新?
    • @fatnjazzy ,这不会触发事件,因为这是使用直接 mysql 查询而不是 eloquent。如果你想使用 eloquent,你必须先找到/选择。您可能希望手动触发事件。
    【解决方案2】:

    一个肮脏的解决方案:

    // Create an instance without insert to database.
    $instance = new ResearchModel;
    $instance->id = 2;
    $instance->name = "test";
    
    // Set the instance status directly.
    $instance->exists = true;
    
    // Update database without model.
    ResearchModel::where('id', $instance->id)
        ->update(['name' => $instance->name]);
    
    // Manually trigger event.
    event('eloquent.updating: App\ResearchModel', $instance);
    

    这种方法的前提是你已经有了需要的数据。如果必须从DB中读取事件所需的数据,那么这种方法是没有用的。

    【讨论】:

      【解决方案3】:

      按id查找

      $research = ResearchModel::find(2);
      

      然后你就可以运行更新功能了

      $research->update([ 'name' => "test"]);
      
      

      如果你不想使用

      ResearchModel::find(2);
      

      那么你必须使用路由绑定

      https://laravel.com/docs/6.x/routing#implicit-binding

      【讨论】:

      • 谢谢,但我的用例与路由无关,此更新不是由客户端触发的。
      • @fatnjazzy 那么你想更新什么。?孔表或特定行。?如果具体,那么您将需要 id 对吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多