【问题标题】:Can not update a boolean value in table by vue and laravel无法通过 vue 和 laravel 更新表中的布尔值
【发布时间】:2020-07-31 20:16:13
【问题描述】:

当我尝试将单个或多个记录从 false 更新为 true 时,我有一个布尔字段,但当尝试将其更新回 false 时,它​​仅适用于第一条记录,不能重复更新多条记录同时不刷新页面1-我处理请求的vue组件是这样的:

<template>
<div v-for="(channel, index) in items" :key="channel.id">
<a href="" @click.prevent="toggleVisibility(channel)">
<i v-if="channel.active" class="fas fa-stop default-stop" data-toggle="tooltip" title="Stop Channel"> 
</i>
<i v-else class="fas fa-play" data-toggle="tooltip" title="Start Channel"></i>
</a>
</div>
</template>

export default {
    name: "Channels",
    props: ['allChannels'],
    data() {
        return {
            items: this.allChannels
        }
    },
    methods: {
        toggleVisibility(channel) {
            axios[channel.active ? 'delete' : 'post'](`/visible-channels/${channel.name}`);
        }
    }
}

还有我的路线:

Route::post('/visible-channels/{channel}', 'ChannelsController@activate');
Route::delete('/visible-channels/{channel}', 'ChannelsController@deactivate');

我的控制器:

public function activate(Channel $channel, Request $request)
{
    if ($request->method() == 'POST') {
        $channel->update(['active' => true]);
    }
    return back();
}

public function deactivate(Channel $channel, Request $request)
{
    if ($request->method() == 'DELETE') {
        $channel->update(['active' => false]);
    }
}

型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Channel extends Model
{
protected $guarded = [];

protected $casts = [
    'active' => 'boolean',
];

protected static function boot()
{
    parent::boot(); 

    static::updating(function () {
        return Cache::forget('activeChannels');
    });
}

public function getRouteKeyName()
{
    return 'name';
}
}

【问题讨论】:

    标签: laravel vue.js laravel-5


    【解决方案1】:

    由于 laravel 在数据库中将布尔值存储为 10,因此您可能应该在模型中将 active 属性设置为 boolean

    这是因为 laravel 将 false 视为字符串,因此当您将 active 设置为 false 时,它​​会将其与 'false' == true 进行比较,即 true,因此它将 1 存储在数据库中。

    class Channel extends Model
    {
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'active' => 'boolean',
        ];
    }
    

    【讨论】:

      【解决方案2】:

      我发现只是在启动功能中更改以等待更新完成

       static::updated(function () {
          return Cache::forget('activeChannels');
      });
      

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-20
        • 2020-06-27
        • 2022-11-10
        • 2017-03-05
        • 2014-08-07
        相关资源
        最近更新 更多