首页 > 解决方案 > Time column value change without touching it

问题描述

I have a "Trip" model that has "time" column that represents the trip time (in addition to the created_at and updated_at) columns. There's a hasOne relation between the "Trip" model and a "Bus" model (every bus can be associated to more than 1 trip). I want to set the "bus_id" column in the "Trips" table to null on deleting the corresponding bus. When I do so, something very strange happens, the "time" column in the "Trips" table changes to the current time (similar to updated_at).

Note:

Trip Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Trip extends Model
{
    //
    protected $fillable = ['time', 'bus_id'];

    public function getStationsStringified(){
        $stations = $this->stations()->orderBy('order', 'asc')->pluck('name')->toArray();
        return implode(",", $stations);
    }

    public function bus(){
        return $this->belongsTo(Bus::class);
    }

    public function tickets(){
        return $this->hasMany(Ticket::class);
    }

    public function stations(){
        return $this->belongsToMany(Station::class)->withPivot("order");
    }
}

Bus Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bus extends Model
{
    //
    protected $fillable = ['license_num'];

    public function trips(){
        return $this->hasMany(Trip::class);
    }
}

Destroy function in BusController:

public function destroy($id){
        $bus = Bus::find($id);

        foreach ($bus->trips as $trip){
            if($trip->time < Carbon::now()->startOfDay()){
                $trip->bus()->dissociate();
                $trip->save();
            }else{
                return new Response("There a trip ".$trip->getStationsStringified()." associated with this bus, please change its bus before deletion", Response::HTTP_CONFLICT);
            }
        }

        $bus->delete();

        return new Response("Deleted", Response::HTTP_OK);
    }

标签: mysqllaraveleloquent

解决方案


The problem was that I used timestamp() in the migrationn file defining the trips table, which adds automatically extra function on the time column set to current time on update.

The reason why the problem doesn't happen on any other updates is that I was setting a value to the time column.

The solution is to use datetime() in the migration instead of timestamp().


推荐阅读