简体   繁体   中英

How to update multiple rows and database with same value at once? Laravel

I'm stuck in code. I managed to create a form that adds a multiple number of rows in db but I do not know how to update them at the same time when i need to use product_code as id.

This is table 1 (products) structure:

id | product_name | product_code
1  | Name1        | 101
2  | Name2        | 102
3  | Name3        | 103
4  | Name4        | 104

This is table 2 (products_ing) structure:

 id | product_code | ing_name | ing_weight 1 | 101 | INGName1 | 110 2 | 101 | INGName2 | 10 3 | 101 | INGName3 | 54 4 | 101 | INGName4 | 248 

This is edit function:

    public function post_edit($id = null)
{

    if(Input::get('submit'))
    {
        // ID
        if($id !== null)
        {
            $id = trim(filter_var($id, FILTER_SANITIZE_NUMBER_INT));
        }


        $input = Input::all();

        $validation = Validator::make($input);

        else
        {
            foreach ($input as $key => $value)
            {
                $input[$key] = ($value !== '') ? trim(filter_var($value, FILTER_SANITIZE_STRING)) : null;
            }

            try
            {

                DB::table('products')
                    ->whereIn($id)
                    ->update(array(
            'product_name'          => $items['product_name'],
            'product_code'          => $items['product_code']
                ));


            }

    }

    return $this->get_edit($id);
}

With this I can only edit *product_name* and product_code from products table by id. But I'm trying to update multiple rows from db with same product_code that would serve as id.

// I found on Google images one good image that explains what I'm trying to do but with Laravel:

IMAGE LINK

Is there a solution? Thank you in advance!

Assuming you are using MySQL: Let the database's foreign key do this for you, with the ON UPDATE CASCADE command. This will update all referenced tables if you change the product_code in your base products table.

CREATE-Script of products_ing

...
product_code INT NOT NULL REFERENCES products(product_code) ON UPDATE CASCADE
...

As laravel migration

Schema::create('products_ing', function($table) {
    $table->increments('id');
    $table->int('product_code');
    $table->string('ing_name');
    $table->int('ing_weight');

    /* All the other key stuff */
    $table
        ->foreign('product_code')
        ->references('product_code')
        ->on('products')
        ->onUpdate('cascade');
});

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