【问题标题】:How to get product after insert and update in query builder如何在查询生成器中插入和更新后获取产品
【发布时间】:2019-06-12 21:36:08
【问题描述】:

当创建和更新将返回模型时,我试图获得与 Eloquent 中相同的结果。

在查询生成器的情况下,当insert返回布尔值并且update返回更新行的ID时,我如何返回模型?!?!?

例如:DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0] );

将返回布尔值,而不是我正在寻找的是获取创建的用户,与 User::create() 的行为相同。

DB::table('users')->update() 将返回更新行的 ID,我希望更新的行作为与User::update() 相同的行为的对象。

我知道当我使用insert()insertGetId() 会给我ID,但我不想做额外的步骤来使用ID 并找到行。

另外,对于更新,我不想使用update() 返回的 ID 来使用它来查找行。

这有意义吗?

【问题讨论】:

标签: laravel laravel-5 laravel-query-builder


【解决方案1】:

使用insertGetId() 代替insert(),然后使用find() 模型。例如:

$id = DB::table('users')->insertGetId(['name' => 'Ivanka', 'email' => 'ivanka@ivanka.com']); 
$user = User::find($id);

当您更新时,您有 id,所以只需 find() 它:User::find($id)

解释insertGetId() 工作原理的文档:https://laravel.com/docs/5.7/queries#inserts

【讨论】:

  • 我不是在找这个。 DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0] );上面的代码将返回布尔值。相反,我正在寻找的是检索创建的用户,相同的行为,例如 User::create()。
  • 如果要检索模型,请使用 ORM 或使用我建议的方法。您不能(也不应该)让查询构建器充当 Eloquent ORM,因为两者有不同的用途。
【解决方案2】:

另外,如果需要,您可以从下面的代码中使用。

找到最后一个插入列:

$last_id = Illuminate\Support\Facades\DB::getPdo()->lastInsertId();

接下来:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多