php - Laravel 一对一关系错误不知道为什么?

标签 php laravel laravel-8 relationship one-to-one

显示错误

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Database\Eloquent\Relations\HasOne given, called in G:\Laravel\practice-1\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72

用户模型

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    public function book()
    {
        # code...
        return $this->hasOne(Book::class);
    }
}

图书迁移

<?php

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

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('abut');
            $table->float('amount', 8, 2);
            $table->timestamps();
        });
    }

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

Route::get('/user/{id}/book', function ($id) {
    return User::find($id)->book();
});

我不知道为什么会看到这个错误。我也查看了文档,但没有找到帮助。

最佳答案

你的定义很好。但这个声明:

return User::find($id)->book();

返回一个 Illuminate\Database\Eloquent\Relations\HasOne 对象。

这不是有效的回复内容。尝试将其更改为:

return User::find($id)->book;

关于php - Laravel 一对一关系错误不知道为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71062808/

相关文章:

javascript - 如果用户将产品添加到购物车但从未结账,则检测 session 过期以恢复库存

php - Laravel 5 基于 .env.master 加载 env 文件?

php - 如何在 laravel 函数中添加 php 变量

laravel 8 外键

php - HttpKernel\Exception\MethodNotAllowedHttpException : The GET method is not supported for this route. Supported methods: POST in Laravel

javascript - 通过 PHP 连接具有相同名称的输入值

php - 显示 Bootstrap 动态模态

javascript - 安排 PHP 文件运行

mysql - Laravel - 如何使用不是整数的外部主键?

php - 如何在 Laravel 中明智地获得产品类别?