我有两个表。
第一个表名是user。
User_id, User_name
第二个表名是问题
Question_id, Question, User_id
我想在调用问题表时查看用户名。
表格连接代码:
public function user()
{
return $this->belongsTo(User::class);
}
资源代码为:
public function toArray($request)
{
return[
'Question' => $this->Question,
'created_at' => $this->created_at->diffForHumans(),
'user' => $this->user->name
];
}
问题控制器显示功能:
public function show(Question $question)
{
return new QuestionResource($question);
}
以下代码中的操作错误:
{
"message": "Class 'App\Model\User' not found",
"exception": "Symfony\Component\Debug\Exception\FatalThrowableError",
"file": "C:\xampp\htdocs\forumapp\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php",
"line": 718,
"trace": [
{
"file": "C:\xampp\htdocs\forumapp\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php",
"line": 179,
"function": "newRelatedInstance",
"class": "Illuminate\Database\Eloquent\Model",
"type": "->"
},
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class User extends Model
{
protected $table = 'user';
}
创建一个Elquent模型类,因为您使用了'return$this->belongsTo(User::class(;'此处的用户类定义精灵关系。希望对你有用。