在 laravel 中调用 null 上的成员函数attach()

问题描述 投票:0回答:1

我的项目任务和办公室表中有多对多关系: 任务模型:

public function offices(): BelongsToMany 
    {
        return $this->belongsToMany(Office::class)->withPivot('main_office'); 
    }

办公模式:

public function tasks(): BelongsToMany    
    {       
        return $this->belongsToMany(Task::class)->withPivot('main_office');
    }

控制器中的存储功能:

public function store(taskRequestStore $request,TaskService $service)
    {
        $offices=Office::where([['top_office_id',null],['status',1]])->get();
        $attributes = $request->all(['Caption','TaskDsc','TaskDate','Priority_id',
                                'Type','TaskFile','FilePath','StartDate','EndDate','Deadline',
                                'Commander_id','Status_id'
                                ]);
        $tasks = $service->create($attributes);
        // dd($tasks,$offices);
        $tasks->$offices->attach([1]);
       return redirect()->back();
    }

记录已插入到任务表中,但附加命令发出错误。

当活动 dd 时:

enter image description here

我的代码错误在哪里?

laravel
1个回答
0
投票

您的问题是这一行:

$tasks->$offices->attach([1]);

应该是:

$tasks->offices()->attach($offices);

因为您想要将办公室附加到任务,所以您必须调用关系(

offices()
而不是
offices
)并传递您想要附加的内容。

如果使用

attach($offices)
不起作用,请使用
->attach($offices->pluck('id')->toArray())

不过,您的问题是

$offices
为空,因此当您运行
->get()
时您无法获取数据,因此它永远不会附加任何内容

© www.soinside.com 2019 - 2024. All rights reserved.