【问题标题】:Laravel save() if relation already existLaravel save() 如果关系已经存在
【发布时间】: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


    【解决方案1】:

    Belongs To Relationships

    来自文档

    $account = App\Account::find(10);
    $user->account()->associate($account);
    $user->save();
    

    【讨论】:

      【解决方案2】:

      如果您尝试将一个模型附加到另一个模型,请使用 attach() 方法而不是 save 和 ID 而不是对象:

      $parent->childs()->attach($child->id);
      

      如果您尝试创建一个新对象,请使用findOrNew() 而不是find()

      $child = Task::findOrNew(request('child'));
      

      如果新对象尚不存在,此方法将创建一个新对象。

      【讨论】:

      • 我尝试了您的解决方案,但我仍然有一个 Integrity violation 使用 attach() 方法。我认为我没有正确地提出我的问题,所以我修改了我的帖子
      • @Raccoon 听起来你没有正确定义关系。
      • 我添加了我的关系定义,你能看一下吗?
      • @Raccoon 关系很好。然后你使用了错误的 ID 和附加。确保传递现有对象的 ID,并确保它是 ID 而不是对象。
      • 我确定,我 dd() 提出了请求,是的,我有正确的 ID。您确定attach() 管理关系已经存在的情况吗?我在文档中找不到任何内容。
      猜你喜欢
      • 2015-07-02
      • 2021-11-04
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2021-05-12
      • 2018-04-07
      相关资源
      最近更新 更多