简体   繁体   中英

How Update a data from an object of json type column in Laravel?

I have an object of json type column in my table (properties) in MySQL like:

[
    {
        "unit": "2",
        "floor": "1",
        "price": "6000000",
        "toilet": "2",
        "balcony": "2",
        "bedrooms": "2",
        "customer": "3",
        "bathrooms": "3",
        "flat_name": "1A",
        "flat_size": "1200",
        "floor_plan": "217",
        "price_per_sqft": "5000"
    },
    {
        "unit": "2",
        "floor": "1",
        "price": "5000000",
        "toilet": "2",
        "balcony": "2",
        "bedrooms": "2",
        "customer": null,
        "bathrooms": "3",
        "flat_name": "1B",
        "flat_size": "1200",
        "floor_plan": "215",
        "price_per_sqft": "5000"
    },
    {
        "unit": "1",
        "floor": "2",
        "price": "6000000",
        "toilet": "2",
        "balcony": "2",
        "bedrooms": "2",
        "customer": null,
        "bathrooms": "3",
        "flat_name": "2A",
        "flat_size": "1250",
        "floor_plan": "216",
        "price_per_sqft": "5300"
    }
]

How can I update customer id, where flat_name = 1B from this object in Laravel?

I have made the solution with using loop. Thank you who reply and answer

$objectitem=Property::where("id", 1)->first();
$updatedFlatDetails= $objectitem->flat_details;

foreach ($objectitem->flat_details as $key => $singleflat){
    if($singleflat['flat_name']==$item->flat_name){
        $updatedFlatDetails[$key]['customer']=(string)$item->customer_id;
    }
}

$objectitem->flat_details = $updatedFlatDetails;
$objectitem->save();

Use collection after fetch data from database:

$target= $collection->filter(function ($item) {
    return $item->flat_name=="1B";
})->values();

or filter before fetch data use eloquent:

Model::where('flat_name','1B')->get(); 

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