Php Laravel 5.1建议的关系设置
我正在建立一个时间表系统,并为时间表建立了一个模型。时间表可以有许多行—例如,当我添加时间表时,我可以向时间表添加许多天(行) 我希望在保存时间表时能够同步行。例如,将向数据库中添加新行,将从数据库中删除给定数组中缺少的行 我知道我可以使用像这样工作的Php Laravel 5.1建议的关系设置,php,laravel,laravel-5,Php,Laravel,Laravel 5,我正在建立一个时间表系统,并为时间表建立了一个模型。时间表可以有许多行—例如,当我添加时间表时,我可以向时间表添加许多天(行) 我希望在保存时间表时能够同步行。例如,将向数据库中添加新行,将从数据库中删除给定数组中缺少的行 我知道我可以使用像这样工作的sync方法,但是,我不认为我需要归属关系。目前,我的行关系设置为有许多。时间表模型如下所示: <?php namespace App\Models\Timesheet; use Illuminate\Database\Eloquent\
sync
方法,但是,我不认为我需要归属关系。目前,我的行
关系设置为有许多
。时间表模型如下所示:
<?php
namespace App\Models\Timesheet;
use Illuminate\Database\Eloquent\Model;
class Timesheet extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'timesheet';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['user_id', 'week', 'year', 'token', 'total_hours'];
/**
* Define that we want to include timestamps.
*
* @var boolean
*/
public $timestamps = true;
/**
* Boot the model.
*
*/
public static function boot()
{
parent::boot();
static::deleting(function($timesheet)
{
$timesheet->row()->delete();
});
}
/**
* The rows that belong to the timesheet.
*
* @return Object
*/
public function row()
{
return $this->hasMany('App\Models\Timesheet\RowTimesheet');
}
}
我需要做些什么才能让这样的事情成功:
$this->timesheet->find($id)->row()->sync($data);
提前感谢。我相信“同步”方法适用于“归属关系”。
你拥有的是“有很多”的关系,为此你需要做如下的事情
对hasMany关系使用“保存”方法而不是“同步”
$data = new App\Comment(['message' => 'A new comment.']);
$this->timesheet->find($id)->row()->save($data); // saves single row sheet object for a timesheet
$this->timesheet->find($id)->row()->saveMany($multipleData); // saves multiple row sheet objects for a timesheet
$data = new App\Comment(['message' => 'A new comment.']);
$this->timesheet->find($id)->row()->save($data); // saves single row sheet object for a timesheet
$this->timesheet->find($id)->row()->saveMany($multipleData); // saves multiple row sheet objects for a timesheet