简体   繁体   中英

Laravel 5.4 - Issue with query builder

I have a table called "Characters". Each row is identified by / has a primary key called char_id. I have routes and templates working as well as some controllers with some CRUD, so Laravel is working fine.

I want to be able to display a row, identified by the rows id, when a user goes to "character/{char_id}" eg "character/2".

I have the following code in my web route:

Route::get('characters/{char_id}', function($char_id) {
    $character = \DB::table('characters')->find($char_id);
    dd($character);
});

But when I visit "characters/1" or any other number I get this error:

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from characters where id = 1 limit 1)

It seems to be looking for a column called "id" regardless of what I try to pass from the URL. I'm following a tutorial that uses "id" so I suspect my code is looking for a column called "id" but I don't know how to get around that.

It's because by default find checks the id column, the easiest way to fix this without using models is to make the where yourself :

 $character = \DB::table('characters')->where('char_id', $char_id)->first();

However, if you have a Character model, you can just set :

protected $primaryKey = 'char_id';

and then use find :

App\Character::find($char_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM