0

我有 2 张桌子。

第一个表名是用户。

User_id, User_name

第二个表名是 Question


Question_id, Question, User_id

我想在调用 Question 表时查看用户名。

表连接代码:

 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": "->"
        },
4

1 回答 1

0
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

 class User extends Model
 {


    protected $table = 'user';
 }

创建一个 Elquoent 模型类,因为您使用了 'return $this->belongsTo(User::class);' 用户类在这里定义 elquent 关系。希望它对你有用。

于 2019-11-11T19:33:32.650 回答