错误调用成员函数attach()时为null

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

我想创建标签系统,但出现错误“错误在null上调用成员函数attach()。请看我的代码

关系:]

Job.php

public function services(){
        $this->belongsToMany('App\Jobervices');
    }

Jobservices.php

public function jobs(){
    $this->belongsToMany('App\Job');
}

并且我创建了数据透视表

Schema::create('job_jobservices', function (Blueprint $table) {
    $table->id();
    $table->integer('job_id');
    $table->integer('jobservices_id');
    $table->timestamps();
});

控制器和视图]

我尝试将控制器附加到服务中。看这个。

$job = Job::create([
           'title'          => $request->title,
           'description'     => $request->description,
           //...
        ]);
$job->services()->attach($request->services);

我认为,$ request-> services很好,因为如果我尝试dd($ request-> services),它会显示我this,以防万一我告诉你我的观点

<select class="js-example-responsive col-12" multiple="multiple" name="services[]">
    @foreach($services as $service)
        <option value={{ $service->id }}>{{ $service->name }}</option>
    @endforeach
</select>
    @error('services')
        <div class="alert alert-danger" role="alert">
        {{ $message}}
        </div>
    @enderror

我不知道为什么,但是显示给我一个错误

错误调用成员函数attach()时为null

你知道怎么了吗?

php mysql laravel relationship
1个回答
0
投票

您应该和亲戚一起回来。

public function services()
{
    return $this->belongsToMany('App\Jobervices');
}
public function jobs()
{
    return $this->belongsToMany('App\Job');
}
© www.soinside.com 2019 - 2024. All rights reserved.