【问题标题】:Laravel 5.4 Call to a member function attach() on null while inserting in pivot tableLaravel 5.4 在插入数据透视表时在 null 上调用成员函数 attach()
【发布时间】:2018-05-27 00:26:36
【问题描述】:

我在数据透视表中插入数据时遇到了一些问题。 当我使用 return dd($request->education); 时,我已经成功获取了数组。

但是当我使用附加时

foreach($request->education as $education) { $preq->教育()->附加([ 'education_id' => $教育 ]); }

$preq->education()->attach([ 'education_id' => $request->教育 ]);

得到一些错误Call to a member function attach() on null

这是我的 Preq 模型

class Preq extends Model {  
    protected $table = 'preqs';

    public function education()
    {
        $this->belongsToMany(Education::class)->withTimestamps();
    }
}

【问题讨论】:

  • 您缺少return 语句。并确保添加一个带有教育类路径的 use 语句:use App\Education。您还应该在解决后关闭它。

标签: php mysql pivot-table laravel-5.4 laravel-eloquent


【解决方案1】:

要链接你需要从education()返回对象

class Preq extends Model {  
    protected $table = 'preqs';

    public function education()
    {
        return $this->belongsToMany(Education::class)->withTimestamps();
    }
}

【讨论】:

  • 得到了一些像这样的错误SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'SD' for column 'education_id' at row 1 (SQL: insert into education_preq` (created_at, education_id, preq_id, updated_at) 值 (2017-12-13 07:30:53, SD, 12, 2017-12-13 07:30:53))`
  • 试试:return $this->belongsToMany(Education::class, 'preqs')->withTimestamps();
猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2021-05-23
  • 2017-12-04
  • 2014-09-15
相关资源
最近更新 更多