首页 > 解决方案 > Laravel 表关系获取评论->用户名(id)

问题描述

我正在尝试显示作为每个评论块一部分的用户名。目前我已经得到它来显示文章+评论和评论的正文,但在我的表格中,我已经为每个评论分配了 user_id。我可以让它显示 user_id,但我不确定如何查找分配给该 user_id 的用户名。

看法:

@foreach($article->comments as $comment)
        {{$comment->user->username}}
              {{$comment->body}}
@endforeach

模型文章:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Articles extends Model
{
    public function comments(){
        return $this->hasMany('App\comments')->orderBy('id', 'DESC');
    }
}

型号评论:

namespace App;

use Illuminate\Database\Eloquent\Model;

class comments extends Model
{
    public function user(){
        return $this->hasOne('App\users');
    }
}

文章控制器:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Articles;
use App\Comments;
use App\Users;


class ArticlesController extends Controller
{
    public function getAllArticles(){
        $results = Articles::orderBy('id', 'DESC')->get();
        return view('index', ['articles' => $results]);
    }
}

错误:

SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'users.comments_id'(SQL:select * from users where users. comments_id= 16 and `u ▶"

标签: phplaravel

解决方案


你在comments课堂上使用了无效的关系。

使用belongsTomethod 代替hasOne,如下所示

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class comments extends Model
{
    public function user(){
        return $this->belongsTo('App\users')->withDefault([
            "username"=>null
        ]);
    }
}

推荐阅读