没有 id 的 Laravel 5 更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36270417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 update without id
提问by OrgGila
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?
我在 Laravel 5 中遇到问题。当我更新数据库中的记录时,出现错误Unknown column 'id' in 'where clause'
。在控制器中,我使用 WHERE 子句来获取我想要更新的记录。我的主键不是 id,类型是 bigInteger。我试过添加protected $primaryKey
模型,但它不适用于 bigInteger。有什么办法可以使用我自己的主键而不是使用 id 吗?
Controller
控制器
$item = Item::where('item_id','=',$item_id)->first();
$item.name = $name;
$item.type = $type;
$item.save();
回答by terry low
pls add this line to your Item.php model
请将此行添加到您的 Item.php 模型中
class Item extends Model {
class Item extends Model {
// add this line only protected $primaryKey = 'item_id';
// 只添加这一行 protected $primaryKey = 'item_id';
//..... the rest of your model
//..... the rest of your model
since your using custom id name, laravel will not know what is your primary key without you specify it
由于您使用自定义 id 名称,如果您不指定,laravel 将不知道您的主键是什么
回答by qiyon
Laravel's orm $primaryKey
default is 'id'
.
Laravel 的 orm$primaryKey
默认是'id'
.
When orm update, it use the sql like:
当 orm 更新时,它使用的 sql 如下:
... where {$this->primaryKey} = {$this->{$this->primaryKey}}
So when you class extends orm.
所以当你上课时扩展orm。
You should redefine protect $primaryKey = '<your_table_primary_key>';
.
你应该重新定义protect $primaryKey = '<your_table_primary_key>';
.
回答by CanKer DiAlike
Try this $item = Item::where('item_id', $item_id)->first();
If still don't working add also protected $primaryKey = "item_id";
to your model
试试这个$item = Item::where('item_id', $item_id)->first();
如果仍然不起作用,也添加protected $primaryKey = "item_id";
到您的模型中