Laravel 5.5急切加载抛出错误 - 试图获取非对象的属性

时间:2018-02-11 19:05:00

标签: php mysql laravel-5 eloquent eager-loading

我看到很多人在热切的装载和Laravel方面遇到了麻烦,我也是其中之一。 我收到错误:试图获取非对象的属性

解决方案:我需要在模型中加入public $incrementing = false;。请参阅底部的扩展答案

我查看了其他堆栈溢出答案,但没有一个解决了这个问题:这里的全部我的代码

我的2个迁移文件

create_authors_table

<?php

# database/migrations/1970_01_01_000001_create_authors_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAuthorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->string('author_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();

            $table->primary('author_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('authors');
    }
}

create_books_table

<?php

# database/migrations/1970_01_01_000002_create_books_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->string('book_id');
            $table->string('title');
            $table->string('author_id');
            $table->timestamps();

            $table->foreign('author_id')->references('author_id')->on('authors');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

接下来,这是我的路线

路由/ web.php

<?php

# routes/web.php
Route::get('/books', 'BookController@index');

我有2个模特

模型/ Author.php

<?php

# app/Models/Author.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    protected $primaryKey = 'author_id';

    public function book()
    {
        return $this->hasMany('App\Models\Book');
    }
}

模型/ book.php中

<?php

# app/Models/Book.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'book_id';

    public function author()
    {
        return $this->belongsTo('App\Models\Author', 'author_id');
    }
}

这是我的 BookController

<?php

# app/Http/Controllers/BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Book;

class BookController extends Controller
{
    public function index()
    {
        $books = Book::with('author')->get();


        $results = [];
        foreach ($books as $book) {
            $result = new \stdClass();
            $result->title = $book->title;
            $result->author_first_name = $book->author->first_name;
            $result->author_last_name = $book->author->last_name;
            $results[] = $result;
        }

        dd($results);
    }
}

以下是一些填充数据库的测试数据:

insert into authors (author_id, first_name, last_name, created_at) 
values 
(
  'ceefb81f-48bb-ff07-1002-27fd8b7272b4', 'Charles', 'Coal', '2018-02-11 00:00:00'
);

INSERT INTO books (book_id, title, author_id, created_at)
VALUES 
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b337', 'Killing Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:00'
),
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b338', 'Cleaning Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:01'
),
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b339', 'Using Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:02'
);

我已开启登录MySQL,可以看到正在运行2个查询

# turn on logging by running the following in MySQL
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/tmp/mysql.logfile.log";
SET GLOBAL general_log = 'ON';

这是MySQL日志文件的输出

2018-02-11T18:52:21.426064Z   262 Prepare   select * from `books`
2018-02-11T18:52:21.426348Z   262 Execute   select * from `books`
2018-02-11T18:52:21.426539Z   262 Close stmt    
2018-02-11T18:52:21.430560Z   262 Prepare   select * from `authors` where `authors`.`author_id` in (?)
2018-02-11T18:52:21.430689Z   262 Execute   select * from `authors` where `authors`.`author_id` in ('ceefb81f-48bb-ff07-1002-27fd8b7272b4')

但是,出于某种原因,关系没有关联

因为,我使用GUID而不是自动递增整数,我不得不告诉Eloquent主键不是自动递增的。 Laravel幕后试图将我的GUID转换为整数。

<?php
# app/Models/Book.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'book_id';

    # HAD TO ADD THIS
    public $incrementing = false;

    public function author()
    {
        return $this->belongsTo('App\Models\Author', 'author_id');
    }
}

应用/型号/作者

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    protected $primaryKey = 'author_id';

    # HAD TO ADD THIS
    public $incrementing  = false;

    public function book()
    {
        return $this->hasMany('App\Models\Book');
    }
}

1 个答案:

答案 0 :(得分:2)

对于Book模型,您需要定义第三个参数book_id

public function author()
{
   return $this->belongsTo('App\Models\Author', 'book_id', 'author_id');
} 
  

如果您的父模型不使用id作为其主键,或者您希望使用   要将子模型加入到不同的列,您可以传递第三个   belongsTo方法的参数,指定父表的自定义   键