【问题标题】:Error Call to a member function attach() on null在 null 上调用成员函数 attach() 时出错
【发布时间】:2020-09-02 05:23:59
【问题描述】:

我想创建标签系统但我有一个错误“错误 在 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

我不知道为什么,但它显示了一个错误

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

你知道哪里错了吗?

【问题讨论】:

    标签: php mysql laravel relationship


    【解决方案1】:

    你应该带着关系回来。

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

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 1970-01-01
      • 2018-05-27
      • 2021-05-23
      • 2022-07-26
      • 2018-01-14
      • 2017-08-09
      • 2020-01-19
      • 2017-09-14
      相关资源
      最近更新 更多