我基本上是试图从我的表中获取一个特定的行并更新它,但是,我最终得到一个集合,其中没有定义保存方法,因为错误在我的标题中说明。你能告诉我下面的代码有什么问题吗?我也尝试过没有get方法。但在那种情况下,我得到了一个不同的错误。另外,如果有更好的方法从表中检索具有两个主键(userId,folderName)的行,请告诉我。谢谢:))
$tempFolder = Message_Folders::where('userId',"=",1)->where('folderName',"=",$imap_folder['name'])->get();
if($tempFolder==null){//If not existing, however in this example assume that it exists
$tempFolder = new Message_Folders();
$tempFolder->userId = 1;
$tempFolder->folderName = $imap_folder['name'];
}
$tempFolder->flags = $imap_folder['status']->flags;
$tempFolder->messages = $imap_folder['status']->messages;
$tempFolder->recent = $imap_folder['status']->recent;
$tempFolder->unseen = $imap_folder['status']->unseen;
$tempFolder->uidnext = $imap_folder['status']->uidnext;
$tempFolder->uidvalidity = $imap_folder['status']->uidvalidity;
$tempFolder->save();
编辑1:
在第一个答案中提到的更新代码后,现在我收到一个新错误。
SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'id'(SQL:update message_folders
set recent
= 4,updated_at
= 2014-03 -08 13:34:10其中id
为空)
请参考下面的代码:(另外,如果所有值都相同,那么它工作正常(因为更新实际上没有发生))
$tempFolder = $this->folders->where('userId',"=",1)->where('folderName',"=",$imap_folder['name'])->first();
if($tempFolder==null){
$tempFolder = new Message_Folders();
$tempFolder->userId = 1;
$tempFolder->folderName = $imap_folder['name'];
}
$tempFolder->flags = $imap_folder['status']->flags;
$tempFolder->messages = $imap_folder['status']->messages;
$tempFolder->recent = 4;
$tempFolder->unseen = $imap_folder['status']->unseen;
$tempFolder->uidnext = $imap_folder['status']->uidnext;
$tempFolder->uidvalidity = $imap_folder['status']->uidvalidity;
$tempFolder->save();
编辑2:上述代码中提到的表的迁移文件的一部分:
public function up()
{
Schema::create('message_folders', function(Blueprint $table) {
$table->integer('userId');
$table->string('folderName', 200);
$table->integer('flags');
$table->integer('messages');
$table->integer('recent');
$table->integer('unseen');
$table->integer('uidnext');
$table->integer('uidvalidity');
$table->timestamps();
$table->primary(array('userId','folderName'));
});
}
答案 0 :(得分:20)
以下行使用Query Builder的 get 方法:
$tempFolder = Message_Folders::where('userId',"=",1)->where('folderName',"=",$imap_folder['name'])->get();
它将从该模型中检索所有行(按过滤条件当然)。所以你得到的是Collection而不是模型的实例。
要从查询中检索单行,您可以使用第一个方法:
//returns a single row from the query
$tempFolder = Message_Folders::where('userId',"=",1)->where('folderName',"=",$imap_folder['name'])->first();