显示错误
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/