猿问

在 null 上调用成员函数 attach() 时出错

我想创建标签系统,但我有一个错误“Error Call to a member function attach() on null”。看看我的代码


关系:


作业.php


public function services(){

        $this->belongsToMany('App\Jobervices');

    }

工作服务.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),它会向我显示 这个,但以防万一我会向您展示我的观点


<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

我不知道为什么,但它向我显示错误


在 null 上调用成员函数 attach() 时出错


你知道哪里出了问题吗?


白衣染霜花
浏览 103回答 2
2回答

温温酱

你应该带着这段关系回来。public function services(){&nbsp; &nbsp; return $this->belongsToMany('App\Jobervices');}public function jobs(){&nbsp; &nbsp; return $this->belongsToMany('App\Job');}

开满天机

我在laravel 7上遇到了这个错误 ,即使我从模型中返回了关系,但没有任何效果。实际上这不是代码错误,最后我用以下方法修复了它:composer updatecomposer dump-autoload在此之后一切正常。型号代号public function adjustments()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->belongsToMany(User::class, 'adjustments')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->withTimestamps();&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答