输入名称而不是用户ID

时间:2019-11-08 11:01:15

标签: laravel-6.2

我有2张桌子。

第一个表名是用户。

User_id, User_name

第二张表的名称为Question


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

1 个答案:

答案 0 :(得分:0)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

 class User extends Model
 {


    protected $table = 'user';
 }

创建Elquoent模型类是因为您已经使用'return $ this-> belongsTo(User :: class);'用户类来定义Elquoent关系。 希望它对您有用。

相关问题