【问题标题】:How to store data into exists row如何将数据存储到存在行
【发布时间】:2019-08-27 01:22:28
【问题描述】:

我编写代码用于在插入新数据时将预订数据插入到我的数据库中,它将创建新行,因此我得到重复的数据,因此如果 schedules_id 等于存在 schedules_id 则我需要存储数据 将座位数据存储到该表中数组格式,我就是这样做的。

$booking = new Bookings();
        $booking->users_id = 4;
        $booking->schedules_id = $schedules_id;
        $booking->buses_id = $buses_id;
        $booking->routes_id = $routes_id;
        $booking->seat = implode(',', $seat);
        $booking->price = $request->price;
        $booking->profile = 'pending';

【问题讨论】:

  • 如果schedules_id 存在,是否只存储seat data
  • 1.你想匹配什么来更新 2. 你有像id 这样的主键吗?
  • @bhavinjr 是的先生
  • @NikleshRaut 是的 bookings_id
  • 请阅读firstOrNew

标签: php laravel


【解决方案1】:

您可以在模型上使用updateOrCreate 方法,所以试试这个:

$booking = Bookings::updateOrCreate(
    ['schedules_id' => $schedules_id, 'users_id' => 4 ], // match the row based on this array
    [ // update this columns
        'buses_id' => $buses_id,
        'routes_id' => $routes_id,
        'seat' => json_encode($seat),
        'price' => $request->price,
        'profile' => 'pending',
    ]

);

【讨论】:

  • 先生,我需要以 JSON 编码的数组格式存储座位数据
  • 假设你的$seat是一个数组,你不需要使用implode,因为它会将它转换为一个字符串,你可以直接在数组上使用json_encode,它会变成一个字符串。那么反过来就是json_decode($seat, TRUE)这个返回数组。
  • 太棒了,先生!
  • 先生正在更新数据,列中只会存储一个数据
  • 那么您需要在使用其他数据更新之前将之前的数据显示到视图中。或者使用另一种方法,首先查找该项目,如果它存在,然后更新现有的添加新字段,或者如果它不存在则创建一个新的。
【解决方案2】:
$booking = Bookings::firstOrCreate(
           ['schedules_id' => $schedules_id ],// row to test if schedule id matches existing schedule id
           [ // update this columns
              'buses_id' => $buses_id,
              'routes_id' => $routes_id,
              'seat' => implode(',', $seat),
              'price' => $request->price,
              'profile' => 'pending',
           ]);

你可以使用这个 firstORcreate laravel 方法。有关其用法的更多说明,请参见此 stackoverflow 页面。

First Or Create

但是,如果您想将数据存储为数组,您可以在数据库中为数据创建文本或 json 字段,并使用 eloquent 序列化来处理它。 https://laravel.com/docs/5.8/eloquent-serialization

另一个堆栈溢出示例,其中回答了有关在 json 中存储数据的问题是 Laravel : How to store json format data in database?

【讨论】:

  • 太棒了,先生!
【解决方案3】:

试试这个

假设 Bookings 是模型

$matchThese = ['schedules_id' => $schedules_id];

Bookings::updateOrCreate($matchThese,[
    'seat'  => implode(',', $seat)
]);

$data = $request->all();

$data['seat'] = implode(',', $seat);

$matchThese = ['schedules_id' => $schedules_id];

Bookings::updateOrCreate($matchThese, $data);

确保您在 Bookings 模型中的 $fillable 中添加了列

你可以在你的模型中进行铸造

protected $casts    = [
        'seat'           =>  'array',
    ];

如果你使用数组转换,那么$data['seat'] 应该是数组

【讨论】:

  • 先生,我需要以 JSON 编码的数组格式存储座位数据
  • 太棒了,先生!
  • 出现错误“htmlspecialchars() 期望参数 1 为字符串,给定数组”
  • 您是否在模型中使用数组转换?
  • 如果你使用数组转换,那么$data['seat'] 应该是数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 2018-05-06
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
相关资源
最近更新 更多