简体   繁体   English

laravel控制器与数据库不匹配

[英]laravel controller not matching database

First apologies for the title, I couldn't think of a better description. 首先为这个道歉,我想不出更好的描述。 I have a controller that is suppose to read a database then return it as an object. 我有一个控制器,它假定要读取数据库,然后将其作为对象返回。 This database recently went through a change in structure, and I re-seeded it. 最近,该数据库的结构发生了变化,我将其重新播种。 My controller code is: 我的控制器代码是:

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

This will result in the following out output: 这将导致以下输出:

70008000 70008000

. However, if I run the same through tinker I get an entirely different result. 但是,如果我通过修补程序运行相同的程序,则会得到完全不同的结果。 Tinker code: App\\Book::where('userId',1)->get(); 修补程序代码: App\\Book::where('userId',1)->get(); will result in several records such as: 将产生一些记录,例如:

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: " htt Illuminate \\ Database \\ Eloquent \\ Collection {#3018全部:[App \\ book {#2996 recordId:1, bookId:“ 7iraCwAAQBAJ” ,userId:1,authorId:1,标题:“ The Lime Street of Lime Street”,isbn: 9780307451064”,描述:“ 1924年,一位波士顿外科医生的妻子参加了关于精神主义的全国性激烈辩论,该运动致力于与死者进行交流。记者戏称她为金发碧眼的石灰街巫婆,但信奉她的信徒她最有声望的倡导者是亚瑟·柯南·道尔爵士,他坚信玛格丽的力量,以至于他敦促她参加由《科学美国人》赞助的有争议的竞赛,她的超自然天赋吸引了四位评委,只剩下一位。为了说服……著名的逃生艺术家哈里·霍迪尼(Harry Houdini)。贾赫尔(Jaher)捕捉了他们的电子公共竞争以及将他们带入彼此轨道的竞争。”,预览:“ http://books.google.com/books?id=7iraCwAAQBAJ&dq = 9780307451071&hl =&source = gbs_api “,封面:” htt p://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", }, p://books.google.com/books/content?id = 7iraCwAAQBAJ&printsec = frontcover&img = 1&zoom = 5&edge = curl&source = gbs_api “,book_status:”阅读“,created_at:” 2019-08-16 12:30:27“, Updated_at:“ 2019-08-16 12:30:27”,},

In the result you will see that I highlighted the bookId. 结果中,您将看到我突出显示了bookId。 That is what I expect to return when I run it through my controller. 这是我通过控制器运行它时希望返回的结果。

EDIT 编辑

Database 数据库

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 Model 口才模型

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');
    }
}

In your controller, you are looping over the result set and echoing the bookId for a single model in the loop. 在您的控制器中,您正在循环结果集,并在循环中回bookId单个模型的bookId And in tinker, you are retrieving the results and tinker outputs the collection to the console. 在修补程序中,您正在检索结果,修补程序将集合输出到控制台。 Doing this in tinker should result the same output as your controller: 在修补程序中执行此操作应产生与控制器相同的输出:

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

Again, in tinker, you are retrieving the result set, not a single record, and a lot of additional data, like model details and so on, will be printed in the console. 同样,在修补程序中,您将检索结果集,而不是单个记录,并且许多其他数据(例如模型详细信息等)将打印在控制台中。 Hope this explanation helps. 希望这种解释有所帮助。

Also, you need to correct the typo in your controller. 另外,您需要更正控制器中的错字。 I assume your model name is Book , not book so you should be using the capital name for the model. 我假设您的模型名称是Book ,而不是book因此您应该使用模型的大写名称。

In order to get only one result, you will need the first() method from laravel. 为了仅获得一个结果,您将需要laravel中的first()方法。 What that does is, it takes the firs record and shows it to you. 所要做的是,它获取第一记录并向您显示。 This method will not iterate (loop) through your result set. 此方法不会迭代(循环)结果集。

So your code in Tinker will be like so: 因此,您在Tinker中的代码将如下所示:

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

This wil return only the firs results bookId . 这只会返回第一个结果bookId

Get() method is used to fetch collections. Get()方法用于获取集合。 Collections comes out as arrays. 集合以数组形式出现。 That is why you are getting several bunch of Data's. 这就是为什么您要获得几堆数据的原因。 All of your fields in the table will be displayed and all of your data will be displayed (depending on the options you give like where('userId', 1) ). 将显示表中的所有字段,并显示所有数据(取决于您提供的选项,例如where('userId', 1) )。 That is called a collection. 这就是所谓的集合。 And to iterate or loop through a collection, you will need to use the foreach loop as you have done in your Question. 要迭代或循环遍历一个集合,您将需要像在Question中一样使用foreach循环。

foreach ($books as $b) {
    echo $b->bookId;
}

The problem here is that you are echo-ing $b->bookId . 这里的问题是您正在回显$b->bookId When you echo in Laravel, it will show you the fields data as a whole number. 当您在Laravel中回显时,它将以整数形式显示字段数据。 Like say, if you have bookId 1000, 2000, 3000, 4000, 5000 the result will come as 10002000300040005000 . 就像说,如果您具有bookId 1000、2000、3000、4000、5000,则结果将为10002000300040005000 However, if you do something like this in your controller: 但是,如果您在控制器中执行以下操作:

foreach ($books as $b) {
  echo "<li>" .$b->bookId. "<li>";
}

The result will be something like this: 结果将是这样的:

  • 1000 1000
  • 2000 2000
  • 3000 3000
  • 4000 4000
  • 5000 5000

If you want to fetch a single Item's bookId you will do something like this (This example assumes that you know the records 'id'): 如果要获取单个Item的bookId,则将执行以下操作(此示例假定您知道记录'id'):

$books = \\App\\Book::where('userId',1)->find(1)->bookId;

Now the bookId of result with the id=1 will be displayed. 现在将显示结果id为1的bookId。

Hope this helps. 希望这可以帮助。 Happy Coding :) 快乐编码:)

Thank you everyone for your help. 感谢大家的帮助。 However, I was way off base. 但是,我离基地很远。 The problem is in my Model. 问题出在我的模型中。 When I changed it around, I meant to change the primary key to be 'recordId', but left it as 'bookId'. 当我更改它时,我打算将主键更改为“ recordId”,但将其保留为“ bookId”。
It would appear that Laravel will read that primary key as an integer. 看来Laravel会将主键读取为整数。 So when I would run the code it would see bookId and think it was primary and then convert it to an integer. 因此,当我运行代码时,它将看到bookId并认为它是主要的,然后将其转换为整数。 So in reality what was happening was this: 所以实际上是这样的:

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

I changed the primary key to 'recordId' and it fixed everything. 我将主键更改为“ recordId”,并修复了所有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM