gpt4 book ai didi

php - laravel Controller 与数据库不匹配

转载 作者:行者123 更新时间:2023-11-29 09:36:20 25 4
gpt4 key购买 nike

首先对标题表示歉意,我想不出更好的描述。我有一个 Controller ,它应该读取数据库然后将其作为对象返回。该数据库最近经历了结构变化,我重新播种了它。我的 Controller 代码是:

$books = \App\book::where('userId',1)->get();
foreach ($books as $b) {
echo$b->bookId;
}

这将产生以下输出:

70008000

。然而,如果我通过修补程序运行相同的结果,我会得到完全不同的结果。修补程序代码:App\Book::where('userId',1)->get();将产生多条记录,例如:

Illuminate\Database\Eloquent\Collection {#3018 all: [ App\book {#2996 recordId: 1, bookId: "7iraCwAAQBAJ", userId: 1, authorId: 1, title: "The Witch of Lime Street", isbn: "9780307451064", description: "In 1924 the wife of a Boston surgeon came to embody the raging national debate over Spiritualism, a movement devoted to communication with the dead. Reporters dubbed her the blonde Witch of Lime Street, but she was known to her followers simply as Margery. Her most vocal advocate was Sir Arthur Conan Doyle, who believed so thoroughly in Margery's powers that he urged her to enter a controversial contest, sponsored by Scientific American. Her supernatural gifts beguiled four of the judges. There was only one left to convince ... the acclaimed escape artist, Harry Houdini. Jaher captures their electric public rivalry and the competition that brought them into each other's orbit.", preview: "http://books.google.com/books?id=7iraCwAAQBAJ&dq=9780307451071&hl=&source=gbs_api", cover: "http://books.google.com/books/content?id=7iraCwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api", book_status: "reading", created_at: "2019-08-16 12:30:27", updated_at: "2019-08-16 12:30:27", },

在结果中,您将看到我突出显示了 bookId。这就是我通过 Controller 运行它时期望返回的结果。

编辑

数据库

public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('recordId');
$table->string('bookId');
$table->integer('userId');
$table->integer('authorId');
//$table->integer('genreId');
$table->string('title');
$table->string('isbn');
$table->binary('description');
$table->string('preview');
$table->string('cover');
$table->string('book_status');
$table->timestamps();
});
//DB::statement('ALTER TABLE books AUTO_INCREMENT = 2000');
}

Eloquent 模型

class book extends Model
{
protected $primaryKey = 'bookId';
protected $fillable = [
'bookId',
'userId',
'authorId',
'title',
'isbn',
'description',
'preview',
'cover',
'book_status'
];
//$guarded = [];
public function authors(){
return $this->belongsTo('App\author','authorId');
}
}

最佳答案

在 Controller 中,您将循环结果集并回显循环中单个模型的 bookId。在tinker 中,您正在检索结果,tinker 将集合输出到控制台。在 Tinker 中执行此操作应该会产生与 Controller 相同的输出:

App\Book::where('userId', 1)->first()->bookId;

同样,在tinker中,您检索的是结果集,而不是单个记录,并且许多附加数据(例如模型详细信息等)将打印在控制台中。希望这个解释有帮助。

此外,您需要更正 Controller 中的拼写错误。我假设您的模型名称是 Book,而不是 book,因此您应该使用模型的大写名称。

关于php - laravel Controller 与数据库不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57525540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com