SQLSTATE [42S22]:找不到列:1054"where子句"中的未知列"id"(SQL:从“歌曲"中选择*,其中"id" = 5限制1) [英] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

查看:58
本文介绍了SQLSTATE [42S22]:找不到列:1054"where子句"中的未知列"id"(SQL:从“歌曲"中选择*,其中"id" = 5限制1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get specific data from the database by using column SongID when a user clicks a link but I am getting this error:

SQLSTATE [42S22]:找不到列:1054'where中的未知列'id' 子句"(SQL:从songs中选择*,其中id = 5个限制1)

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from songs where 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');
            });
    }

推荐答案

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

When you use find(), it automatically assumes your primary key column is going to be id. In order for this to work correctly, you should set your primary key in your model.

因此,在Song.php的类中,添加以下行...

So in Song.php, within the class, add the line...

protected $primaryKey = 'SongID';

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

If there is any possibility of changing your schema, I'd highly recommend naming all your primary key columns id, it's what Laravel assumes and will probably save you from more headaches down the road.

这篇关于SQLSTATE [42S22]:找不到列:1054"where子句"中的未知列"id"(SQL:从“歌曲"中选择*,其中"id" = 5限制1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆