SQLSTATE[42S22]:未找到列:1054 'where clause' 中的未知列 'id'(SQL:select * 来自“歌曲”,其中“id”= 5 极限 1)

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

当用户单击 link 时,我试图通过使用列 SongID 从数据库中获取特定数据,但出现此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from songs where id = 5 limit 1)

控制器Class:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use DB;

class SongsController extends Controller {
    public function index()
    {
        $name = $this->getName();
        $songs = DB::table('songs')->get();
        return view('songs.index', compact('songs','name'));
    }
    public function show($id)
    {
        $name = $this->getName();
        $song = DB::table('songs')->find($id);
        return view('songs.show', compact('song','name'));
    }

    private function getName()
    {
        $name = 'Tupac Amaru Shakur';
        return $name;
    }
}

迁移:

    public function up()
    {
            Schema::create('songs', function($table)
            {
                $table->increments('SongID');
                $table->string('SongTitle')->index();
                $table->string('Lyrics')->nullable();
                $table->timestamp('created_at');
            });
    }
$song = DB::table('songs')->find($id);

这里使用方法find($id)

对于Laravel,如果你使用这种方法,你应该有名为'id'的列并将其设置为主键,这样你就可以使用方法find()

否则使用where('SongID', $id)代替find($id)

当您使用 find() 时,它会自动假定您的主键列将是 id。为了使其正常工作,您应该在模型中设置主键。

因此在 Song.php 中,在 class 中添加行...

protected $primaryKey = 'SongID';

如果有任何可能更改您的模式,我强烈建议您将所有主键列命名为 id,这是 Laravel 假设的并且可能会让您免于更多的麻烦路.

protected $primaryKey = 'SongID';

添加到我的模型后告诉主键,因为它默认使用 id(SongID)

进入对应Controller的Model文件查看主键文件名即可

比如

protected $primaryKey = 'info_id';

此处信息 id 是数据库中可用的字段名称 table

可以在 the docs 的“主键”部分找到更多信息。

我是 运行 laravel 5.8,我遇到了同样的问题。对我有用的解决方案如下:

  1. 我使用 bigIncrements('id') 来定义我的主键。
  2. 我用unsignedBigInteger('user_id')来定义外来的 引用的键。

        Schema::create('generals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('general_name');
            $table->string('status');
            $table->timestamps();
        });
    
    
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('general_id');
            $table->foreign('general_id')->references('id')->on('generals');
            $table->string('category_name');
            $table->string('status');
            $table->timestamps();
        });
    

希望对您有所帮助。