Tar*_*tar 27 php mysql laravel laravel-5
我试图通过使用列SongID
在用户单击链接时从数据库中获取特定数据,但我收到此错误:
SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'id'(SQL:select*from
songs
whereid
= 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;
}
}
Run Code Online (Sandbox Code Playgroud)
移民:
public function up()
{
Schema::create('songs', function($table)
{
$table->increments('SongID');
$table->string('SongTitle')->index();
$table->string('Lyrics')->nullable();
$table->timestamp('created_at');
});
}
Run Code Online (Sandbox Code Playgroud)
use*_*496 77
使用时find()
,它会自动假定您的主键列将是id
.为了使其正常工作,您应该在模型中设置主键.
所以在Song.php
课堂上添加线...
protected $primaryKey = 'SongID';
Run Code Online (Sandbox Code Playgroud)
如果有可能更改您的架构,我强烈建议您命名所有主键列id
,这是Laravel所假设的,并且可能会让您免于更多的麻烦.
小智 5
$song = DB::table('songs')->find($id);
Run Code Online (Sandbox Code Playgroud)
在这里你使用方法 find($id)
对于Laravel,如果你使用这个方法,你应该有一个名为'id'的列并将其设置为主键,这样你就可以使用方法 find()
否则使用where('SongID', $id)
而不是find($id)
到对应Controller的Model文件中查看主键文件名即可
如
protected $primaryKey = 'info_id';
Run Code Online (Sandbox Code Playgroud)
这里的信息 ID 是数据库表中可用的字段名称
更多信息可以在文档的“主键”部分找到。
归档时间: |
|
查看次数: |
76196 次 |
最近记录: |