简体   繁体   English

如何从Laravel中的json类型列的object更新数据?

[英]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:我在 MySQL 的表(属性)中有一个 object 的 json 类型列,例如:

[
    {
        "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?如何从 Laravel 中的这个 object 更新客户 ID,其中 flat_name = 1B?

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:或在获取数据使用 eloquent 之前进行过滤:

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

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

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