【问题标题】:How can I insert data from get() in laravel?如何在 laravel 中从 get() 插入数据?
【发布时间】:2021-09-30 21:45:09
【问题描述】:

我想从 L_Examen_Categorie 表中的 get() 方法中插入数据,但它说:

无法为表中的标识列插入显式值 'L_Examen_Categorie' 当 IDENTITY_INSERT 设置为 OFF 时。 (SQL:插入 进入 [L_Examen_Categorie] ([id], [code], [libelle], [coefficient], [注], [id_examen]) 值 (5, 777, 777, 3, 12, 1))"

这是我的代码

 $categorie = DB::table('P_Examen_Categorie as p')
            ->where('p.id_examen', '=', $request->input('id_examen'))
            ->get();
        foreach($categorie as $cat_item)
        {
            L_Examen_Categorie::insert((array)$cat_item);;
        }

分类回复:

[{id: "5", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"},…]
0: {id: "5", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"}
1: {id: "7", code: "39", libelle: "39", coefficient: "3", Note: "12", id_examen: "1"}
2: {id: "9", code: "777", libelle: "39", coefficient: "3", Note: "12", id_examen: "1"}
3: {id: "10", code: "777", libelle: "777", coefficient: "1", Note: "1211", id_examen: "1"}
4: {id: "11", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"}

【问题讨论】:

  • 试试L_Examen_Categorie::insert( $categorie->toArray());
  • @Yogendra 我收到了这个错误Object of class stdClass could not be converted to string
  • 那么您需要从 $categorie 数据创建一个新数组,然后在 db 中执行插入
  • 我该怎么做?作为一个例子,我的categorie 数据包含(id、code、libelle)和 db L_Examen_Categorie(id、code、libelle)相同
  • 当您获得类 stdClass 的对象时,无法将其转换为字符串。可能它有空的结果。也试试 (array)$categorie;

标签: php laravel


【解决方案1】:

您需要使用“toArray()”方法。此方法将您的集合对象转换为数组,然后插入数据。

$categorie = DB::table('P_Examen_Categorie as p')
->where('p.id_examen', '=', $request->input('id_examen'))
->get()->toArray();

L_Examen_Categorie::insert( $categorie); 

但请确保L_Examen_Categorie 表中存在相同的列

【讨论】:

  • 我仍然收到Object of class stdClass could not be converted to string
  • @drnwork categorie 只返回一个集合还是多个集合?
  • 多个(类别列表)
  • @drnwork 请在您的问题中添加$categorie 回复。
  • @drnwork 正如你提到的 P_Examen_Categorie 表有 ( id,code,libelle) 列那么这是什么 id_examen->where('p.id_examen', '=', $request->input('id_examen'))
【解决方案2】:

在插入之前将对象转换为关联数组。

$categorie = json_decode($categorie, true);

L_Examen_Categorie::insert($categorie);

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2018-12-31
    • 2016-03-19
    • 2020-03-23
    • 2021-07-25
    • 2020-05-01
    • 2018-05-18
    • 2017-04-18
    相关资源
    最近更新 更多