Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 update without id

I have a problem in Laravel 5. When I update a record in database, I get error Unknown column 'id' in 'where clause'. In the controller, I use WHERE clause to get the record I want to update. My primary key is not id and the type is bigInteger. I've tried adding protected $primaryKey in the model but it doesn't work for bigInteger. Is there any way to use my own primary key instead of using id?

Controller

$item = Item::where('item_id','=',$item_id)->first();
$item.name = $name;
$item.type = $type;
$item.save();
like image 342
OrgGila Avatar asked Mar 28 '16 20:03

OrgGila


2 Answers

pls add this line to your Item.php model

class Item extends Model {


// add this line only
protected $primaryKey = 'item_id';

//..... the rest of your model

since your using custom id name, laravel will not know what is your primary key without you specify it

like image 73
terry low Avatar answered Oct 12 '22 05:10

terry low


Laravel's orm $primaryKey default is 'id'.

When orm update, it use the sql like:

... where {$this->primaryKey} = {$this->{$this->primaryKey}}

So when you class extends orm.

You should redefine protected $primaryKey = '<your_table_primary_key>';.

like image 32
qiyon Avatar answered Oct 12 '22 06:10

qiyon