php - Laravel 5.4 在数据透视表中插入时调用 null 上的成员函数 Attach()

标签 php mysql pivot-table laravel-5.4 eloquent

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

但是当我使用附加时

foreach($request->education as $education) { $preq->education()->attach([ 'education_id' => $education ]); }

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

出现一些错误在 null 上调用成员函数attach()

这是我的 Preq 模型

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

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

最佳答案

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

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

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

关于php - Laravel 5.4 在数据透视表中插入时调用 null 上的成员函数 Attach(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787527/

相关文章:

php - 获取括号后的文本

php - 在 Yii Framework 中处理输出

mysql - 减少数据库IO次数或数据操作大小?

mysql - 为 BPM 应用程序生成自动递增的 ID

php - PDO 将撇号添加到 mySQL 查询

python - Pandas 从数据透视表绘图

php - 如何判断传递给 preg_match() 的模式中是否使用了 PREG 命名组?

php - 如何在 mysql 数据库中存储 Twitter 状态 id_str

python - Pandas 中的数据透视表小计

Excel 条件格式随数据透视表扩展?