【问题标题】:Error: Column not found: 1054 Unknown column 'p_categories.id'错误:找不到列:1054 未知列“p_categories.id”
【发布时间】:2021-08-05 10:35:08
【问题描述】:

对于我的 laravel 项目,我创建了产品类别表并将数据添加到表中。现在我需要使用 get 方法获取每个 product_category 详细信息。

这是我创建的产品类别表,

 public function up()
{
    Schema::create('p_categories', function (Blueprint $table) {
        $table->bigIncrements('category_id');
        $table->string('name');
        $table->string('size');
        $table->timestamps();
    });
}

我使用的CategoryController,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PCategory;
class CategoryController extends Controller
{
//
function addPCategory(Request $req)
{
    $pcategory=new PCategory;
    $pcategory->name=$req->input('name');
    $pcategory->size=$req->input('size');
    $pcategory->save();
    return $pcategory;
}

 function getCategory($id)
 {
    return PCategory :: find($id);
 }
}

在我使用的 api.php 中,

  Route :: post('addPCategory',[CategoryController::class,'addPCategory']);
  Route :: get('Category/{id}',[CategoryController::class,'getCategory']);

我在邮递员中收到此错误

  Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p_categories.id' in 'where clause' (SQL: select * from `p_categories` where `p_categories`.`id` = 1 limit 1)

提前感谢您的帮助!

【问题讨论】:

  • 这和javascript有什么关系?

标签: javascript json laravel api postman


【解决方案1】:

您的p_catgeories 表中没有id 列,您可以通过$table-&gt;id() 添加一列,或者您必须使用category_id 而不是id

问题在于::find() 方法默认查找id 列。如果你真的想要category_id 而不是id,你可以覆盖或重写这个函数。

您还可以将:protected $primaryKey = 'category_id'; 添加到您的 PCategroy 模型中,find() 将再次正常工作。

【讨论】:

  • 现在它工作得很好。非常感谢您的帮助!
  • 我很高兴它有效,如果您能接受我的回答,那就太好了。
【解决方案2】:

find($id) 方法假定您的表的索引名为“id”,但您的索引为 category_id。 替换

    return PCategory :: find($id);

    return PCategory :: where('category_id',$id)->first();

我会为我的表使用 id 并避免违反约定。

【讨论】:

  • 非常感谢!
  • 快乐编码。享受查找方法;)。
猜你喜欢
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2019-11-11
  • 2015-02-22
  • 2019-10-13
  • 2018-02-21
相关资源
最近更新 更多