简体   繁体   中英

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

. However, if I run the same through tinker I get an entirely different result. Tinker code: 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 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", },

In the result you will see that I highlighted the 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. 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.

In order to get only one result, you will need the first() method from laravel. 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:

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

This wil return only the firs results bookId .

Get() method is used to fetch collections. 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) ). 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.

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

The problem here is that you are echo-ing $b->bookId . When you echo in Laravel, it will show you the fields data as a whole number. Like say, if you have bookId 1000, 2000, 3000, 4000, 5000 the result will come as 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
  • 2000
  • 3000
  • 4000
  • 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'):

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

Now the bookId of result with the id=1 will be displayed.

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'.
It would appear that Laravel will read that primary key as an integer. So when I would run the code it would see bookId and think it was primary and then convert it to an integer. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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