1364字段'schedule_id'没有默认值

时间:2019-10-08 09:20:59

标签: laravel-5

未找到Schedule_id字段

//控制器代码

public function store(Request $request)
    {

    $schedule = new menu;
    $days = new day;
    $schedule->scheduleName = $request->name;
    $schedule->sensor = $request->sensor;
    $schedule->start_time = $request->start_time;
    $schedule->end_time = $request->end_time;
    $schedule->timestamps = false;
    $schedule->s_daytime = $request->s_daytime;
    $schedule->e_daytime = $request->e_daytime;
    $days->days = $request->days;
    $days->timestamps = false;
    $days->save();
    $schedule->save();




    return view('store');

}

//型号

class menu extends Model
{
    protected $table = "schedule";

    protected $fillable = [
    'scheduleName', 'start_time', 'end_time','sensor','s_daytime','e_daytime',

    ];
    public function days()
    {
         return $this->hasMany('App\day');
    }

}

1 个答案:

答案 0 :(得分:0)

您的问题是,创建记录时menuday的父项

这是怎么做

$schedule = new menu;
$schedule->scheduleName = $request->name;
$schedule->sensor = $request->sensor;
$schedule->start_time = $request->start_time;
$schedule->end_time = $request->end_time;
$schedule->timestamps = false;
$schedule->s_daytime = $request->s_daytime;
$schedule->e_daytime = $request->e_daytime;
$schedule->save();

// First alternative
$day = $schedule->days()->create([
    'days' => $request->days,
    'timestamps' => false, // not sure if it's an attribute in your case
]);

// Second alternative
$day = new day;
$days->days = $request->days;
$days->schedule_id = $schedule->id; // notice this line
$days->timestamps = false;
$days->save();

我也认为您的关系days应该是正确的,但由于您已将数据库名称设置为schedule

,所以我可能是错的
public function days()
{
    // By default, Laravel will expect `menu_id`
    return $this->hasMany('App\day', 'schedule_id');
}

技巧(1):如果$timestamps是public属性,并且始终为false,则最好在模型中进行设置。

技巧(2):假设您做了技巧(1),则可以减少这样的行数

$schedule = menu::create($request->only(
        'name', 'sensor', 'start_time', 'end_time', 's_daytime', 'e_daytime'
    ));

$day = $schedule->days()->create($request->only(
        'days'
    ));