简体   繁体   English

Laravel - 使用单个查询组合多个查询来更新两个表的数据

[英]Laravel - combining multiple queries to update two table's data using single query

In one of my Laravel project, I have to update two table's data within a same scope of a function. 在我的一个Laravel项目中,我必须在函数的同一范围内更新两个表的数据。 At first query, I am trying to update data of a table using following query - 在第一次查询时,我正在尝试使用以下查询更新表的数据 -

        DB::table('parameters')
        ->where($where)
        ->update($data);

In second and third query I am adding and subtracting two column's of another table - 在第二个和第三个查询中,我正在添加和减去另一个表的两列 -

DB::table('categories')
            ->where(['id' => $data['category_id']])
            ->increment('parameters');

DB::table('categories')
            ->where(['id' => $previous_category_id])
            ->decrement('parameters');

Everything is working fine. 一切都很好。 But, now I want to do all these operations within one query execution. 但是,现在我想在一次查询执行中完成所有这些操作。

As far as I understand this there is no way to do this with one query. 据我所知, 一个查询无法做到这一点。

What you are basically doing with the DB:table facade is runnig a MySQL UPDATE statement like: UPDATE <table_name> SET <field_name>=<value> WHERE condition 您基本上使用DB:table Facade运行MySQL UPDATE语句,如: UPDATE <table_name> SET <field_name>=<value> WHERE condition

As you can see an UPDATE query is pointed to exactly one table, not more. 正如您所看到的,UPDATE查询恰好指向一个表,而不是更多。 So for updating multiple tables you need to run multiple UPDATE queries. 因此,要更新多个表,您需要运行多个UPDATE查询。

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

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