php 如何在 Laravel 4 中使用没有 id 的 Eloquent 更新数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17461383/
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
How can I update data with Eloquent without id in Laravel 4
提问by Eugene Wang
When I want to update the FaqTrans
database, but this datase have two primary key (faq_ida and lang) $table->primary(array('lang', 'faq_id'));
. so I don't need a id
column with auto_increment.
当我想更新FaqTrans
数据库时,但是这个数据库有两个主键 (faq_ida 和 lang) $table->primary(array('lang', 'faq_id'));
。所以我不需要id
带有 auto_increment的列。
However, when I use the following code to update the database, the error message hint me there is no id
column.
但是,当我使用以下代码更新数据库时,错误消息提示我没有id
列。
$faq_trans = FaqTrans::where('faq_id','=',$faq_id)->where('lang','=',$lang)->first();
$faq_trans->lang = Input::get('lang');
$faq_trans->body = Input::get('body');
$faq_trans->title = Input::get('title');
$faq_trans->save();
error message
错误信息
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update
FAQtrans
setbody
= ?,updated_at
= ? whereid
is null) (Bindings: array ( 0 => 'adfadaaadfadaa', 1 => '2013-07-04 11:12:42', ))
SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列 'id'(SQL:更新
FAQtrans
集body
= ?,updated_at
= ? whereid
is null)(绑定:数组(0 => 'adfadaaadfadaa',1 => ' 2013-07-04 11:12:42', ))
and when I added an id
column, the code works fine...
当我添加一id
列时,代码工作正常......
are there any way can I update the database without ID column ?
有什么办法可以在没有 ID 列的情况下更新数据库?
采纳答案by Nico Kaag
Laravel / Eloquent doesn't support composite primary keys.
Laravel / Eloquent 不支持复合主键。
When you check the Eloquent Model class, you can see that the primary key can only be a string, which is used to create the WHERE clause.
查看 Eloquent Model 类,可以看到主键只能是字符串,用于创建 WHERE 子句。
回答by Nishchit Dhanani
Write this line into your Model
将此行写入您的模型
public $primaryKey = '_id';
public $primaryKey = '_id';
Where _id is your manual primary key
其中 _id 是您的手动主键
回答by Alex
Pretty simple:
很简单:
FaqTrans::where(
[
'faq_id' => $faq_id,
'lang' => $lang
]
)->update(
[
'body' => $body,
'title' => $title
]
);
回答by mopo922
For anyone who stumbles upon this question in the future (like I did), here's a nice workaround for a composite primary key in Eloquent.
对于将来偶然发现这个问题的任何人(就像我所做的那样),这是 Eloquent 中复合主键的一个很好的解决方法。
This goes at the top of your model class:
这位于模型类的顶部:
protected $primaryKey = array('key1', 'key2');
Then you override the save()
method on your model with this:
然后你save()
用这个覆盖模型上的方法:
public function save(array $options = array())
{
if(!is_array($this->getKeyName()))
return parent::save($options);
// Fire Event for others to hook
if($this->fireModelEvent('saving') === false)
return false;
// Prepare query for inserting or updating
$query = $this->newQueryWithoutScopes();
// Perform Update
if ($this->exists) {
if (count($this->getDirty()) > 0) {
// Fire Event for others to hook
if ($this->fireModelEvent('updating') === false)
return false;
// Touch the timestamps
if ($this->timestamps)
$this->updateTimestamps();
//
// START FIX
//
// Convert primary key into an array if it's a single value
$primary = (count($this->getKeyName()) > 1) ? $this->getKeyName() : [$this->getKeyName()];
// Fetch the primary key(s) values before any changes
$unique = array_intersect_key($this->original, array_flip($primary));
// Fetch the primary key(s) values after any changes
$unique = !empty($unique) ? $unique : array_intersect_key($this->getAttributes(), array_flip($primary));
// Fetch the element of the array if the array contains only a single element
$unique = (count($unique) <> 1) ? $unique : reset($unique);
// Apply SQL logic
$query->where($unique);
//
// END FIX
//
// Update the records
$query->update($this->getDirty());
// Fire an event for hooking into
$this->fireModelEvent('updated', false);
}
// Perform Insert
} else {
// Fire an event for hooking into
if ($this->fireModelEvent('creating') === false)
return false;
// Touch the timestamps
if ($this->timestamps)
$this->updateTimestamps();
// Retrieve the attributes
$attributes = $this->attributes;
if ($this->incrementing && !is_array($this->getKeyName()))
$this->insertAndSetId($query, $attributes);
else
$query->insert($attributes);
// Set exists to true in case someone tries to update it during an event
$this->exists = true;
// Fire an event for hooking into
$this->fireModelEvent('created', false);
}
// Fires an event
$this->fireModelEvent('saved', false);
// Sync
$this->original = $this->attributes;
// Touches all relations
if (array_get($options, 'touch', true))
$this->touchOwners();
return true;
}
Original source: https://github.com/laravel/framework/issues/5517#issuecomment-52996610
原始来源:https: //github.com/laravel/framework/issues/5517#issuecomment-52996610
Update 2016-05-03
更新 2016-05-03
My new favorite way to do this:
我最喜欢的新方法:
回答by Ironwind
Go to your FaqTrans
model and add this.
转到您的FaqTrans
模型并添加它。
public $key = 'faq_id';
That should do it, assuming faq_id
is more important than the lang
应该这样做,假设faq_id
比lang
回答by mushood badulla
If anyone has the same issue.
I used Nishchit Dhanani answer and it worked pretty well which was:
Write this line into your Model
public $primaryKey = '_id';
Where _id is your manual primary key
如果有人有同样的问题。我使用了 Nishchit Dhanani 的答案,效果很好,它是:
将此行写入您的模型
public $primaryKey = '_id';
其中 _id 是您的手动主键
For my case. I had a user table and part of my users are students. So the primary key in my students table was "user_id".
Adding this line in my Student model: public $primaryKey = 'user_id';
对于我的情况。我有一个用户表,我的部分用户是学生。所以我的学生表中的主键是“user_id”。
在我的学生模型中添加这一行: public $primaryKey = 'user_id';
I was able to use the save() method when updating my student object.
更新我的学生对象时,我能够使用 save() 方法。
Hope this helps
希望这可以帮助