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

新手上路,请多包涵

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

SQLSTATE [42S22]:找不到列:1054 ‘where 子句’中的未知列 ‘id’(SQL:select * from songs where id = 5 限制 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');
            });
    }

原文由 Tartar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 373
2 个回答

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

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

 protected $primaryKey = 'SongID';

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

原文由 user1669496 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 DB::table 如上所述,但没有“查找”

 \Illuminate\Support\Facades\DB::table('model_has_roles')->where('model_id', 123)->update(['role_id' => 2]);

原文由 codethesolution 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题