Laravel | Update Query return “ [{”laboratory“:”Bo

2019-09-02 20:01发布

问题:

I have created a hook function in one of my controller to update a field after submitting the form.

The hook should populate the field "laboratory" of the "orders_detail" database with the name of a laboratory.

/* POPULATE the laboratory FIELD */
DB::table('orders_detail')->where('id',$id)->first();
/* dd($id); */

/* REQUESTED VALUE IN ARRAY :   "ordersdetail-productname" => array:1 [▼ 0 => "1" ] : */

$productname = $_REQUEST['ordersdetail-productnameID'][0];
/* dd($productnameID); **RETURN VALUE "1"** */

/* QUERY : select laboratories.laboratory FROM products LEFT JOIN laboratories ON products.laboratoryID = laboratories.id WHERE products.id = productnameID : */

$laboratory = DB::table('products')
                ->join('laboratories', 'products.laboratoryID', '=', 'laboratories.id')
                ->selectRaw('laboratories.laboratory')
                ->where('products.id', '=', $productnameID)
                ->get();

/* dd($laboratory); **RETURNED ARRAY 
        Collection {#3536 ▼
          #items: array:1 [▼
            0 => {#3534 ▼
              +"laboratory": "Boulanger"
            }
          ]
        }** */

/* UPDATE THE laboratory FIELD WITH THE RETURNED VALUE */
DB::table('orders_detail')->where('orderID', '=', $id)
->update(['laboratory'=> $laboratory]);

How can I get rid of "laboratory": "Boulanger" and just keep Boulanger which is the name of the laboratory I want to update the field "laboratory" with.

Thanks for your expertise.

Cheers, Marc

回答1:

Update your laboratory query as,

$laboratory = DB::table('products')
                ->join('laboratories', 'products.laboratoryID', '=', 'laboratories.id')
                ->selectRaw('laboratories.laboratory')
                ->where('products.id', '=', $productnameID)
                ->first();

And $laboratory->laboratory will give you the expected value.

Update as,

/* UPDATE THE laboratory FIELD WITH THE RETURNED VALUE */

if($laboratory->laboratory) {
    DB::table('orders_detail')
       ->where('orderID', $id)
       ->update(['laboratory'=> $laboratory->laboratory]);
}


回答2:

Try this

 $laboratory = DB::table('products')
            ->join('laboratories', 'products.laboratoryID', '=', 'laboratories.id')
            ->where('products.id', '=', $productnameID)
            ->pluck('laboratories.laboratory');


标签: laravel-5 pdo