首页 文章

SQLSTATE [42S22]:未找到列:1054未知列'id' in 'where clause'(SQL:select * from`songs`其中`id` = 5 limit 1)

提问于
浏览
23

我试图通过使用列 SongID 从用户单击链接时获取数据库中的特定数据,但我收到此错误:

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'id'(SQL:select * from id = 5 limit 1)

控制器类:

<?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');
            });
    }

4 回答

  • 57

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

    所以在 Song.php 中,在类中添加行...

    protected $primaryKey = 'SongID';
    

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

  • 5
    $song = DB::table('songs')->find($id);
    

    在这里你使用方法 find($id)

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

    否则使用 where('SongID', $id) 而不是 find($id)

  • 3

    只需转到相应Controller的Model文件并检查主键字段名称

    protected $primaryKey = 'info_id';
    

    here info id是数据库表中可用的字段名称

    更多信息可以在the docs的"Primary Keys"部分找到 .

  • 0

    protected $primaryKey = 'SongID';

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

相关问题