简体   繁体   中英

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. 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

As you can see an UPDATE query is pointed to exactly one table, not more. So for updating multiple tables you need to run multiple UPDATE queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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