我正在使用 laravel API 并使用模型关系和资源来获取数据,我不知道它给出这种错误的问题出在哪里,我搜索并尝试了解决方案,但问题仍然存在。
这是我的控制器功能:-
public function show(Question $question)
{
return new QuestionResource($question);
}
这是问题模型:-
class Question extends Model
{
use HasFactory;
protected $guarded = [];
public function getRouteKeyName()
{
return 'slug';
}
public function user(){
return $this->belongsTo (User::class, 'user_id');
}
}
这是用户模型:-
public function question(){
return $this->hasMany(\App\Models\Question::class);
}
这是 QuestionResource 函数:-
public function toArray($request)
{
return [
'title'=> $this->title,
'slug'=>$this->slug,
'body'=>$this->body,
'created_at'=>$this->created_at->diffForHumans(),
'updated_at'=>$this->updated_at->diffForHumans(),
'user_name'=>$this->user->name,
];
}
这是问题表:-
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->text('body');
$table->integer('category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}