【发布时间】:2018-06-28 14:58:23
【问题描述】:
我目前正在使用save() 功能 (doc),因此请将子项保存到父项。但是子级已经依附于父级的情况不处理。
所以我创建了这个:
//Validation stuff
$parent = Task::find( request('parent') );
$child = Task::find( request('child') );
if ( \DB::table('task_has_predecessors')
->where('child_id', request('child'))
->where('parent_id' , request('parent'))
->count() == 0 )
{
if ( $parent->childs()->save($child) )
{
flash('Link saved.');
}
else
{
flash()->error('Unable to create the link.');
}
}
else
{
flash()->warning('This link already exist.');
}
但我不是这个解决方案的忠实拥护者......有没有更好的方法可以在不使用 if ( \DB::table('...')->where(...)->where(...)->count() == 0 ) 的情况下实现这一目标?
laravel 有管理这种行为的神奇方法吗?
我没有任何与tasks_has_predecessors 表相关的模型。
我的人际关系是这样的:
class Task extends Model
{
public function childs()
{
return $this->belongsToMany(ChecklistCategoryTask::class, 'task_has_predecessors', 'parent_id','child_id');
}
public function parents()
{
return $this->belongsToMany(ChecklistCategoryTask::class, 'task_has_predecessors' , 'child_id' , 'parent_id');
}
}
【问题讨论】:
标签: php laravel relationship