【问题标题】:Return Model of Newly created Multiple records新创建的多条记录的返回模型
【发布时间】:2021-11-13 19:02:11
【问题描述】:

我需要获取新创建记录的模型

$data = [['name' => 'john'], ['name' => 'Doe']];
$result = Model::insert($data);

但是当我检查 $result 变量时,它是布尔值。

如何获取新创建的记录?

【问题讨论】:

标签: php laravel laravel-5 laravel-8 laravel-7


【解决方案1】:

您可以使用 create 代替 insert,例如,

$data = [['name' => 'john'], ['name' => 'Doe']];
$result = Model::insert($data);//instead of this!
$result = Model::create($data);// use this,

那么 $result 关键字将返回最后创建的数据。 如果你正在使用, $result = $model->save(); 方法,你必须返回 $model 变量。不应该返回 $result,因为它只会给你布尔值。

【讨论】:

    【解决方案2】:

    使用fresh() 解决了我的问题

    $data = [['name' => 'john'], ['name' => 'Doe']];
    $result = Model::create($data);
    $data = $result->fresh();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      相关资源
      最近更新 更多