php - 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
whereusers
.comments_id
= 16 and `u ▶"
解决方案
你在comments
课堂上使用了无效的关系。
使用belongsTo
method 代替hasOne
,如下所示
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
public function user(){
return $this->belongsTo('App\users')->withDefault([
"username"=>null
]);
}
}
推荐阅读
- java - 我怎样才能只打印一次字符串?
- java - 类之间共享的随机值实例
- sql - 使用 CTE 获取 XML 路径的值
- java - 如何单击循环并单击具有属性的所有xpath并在控制台中打印获取文本?
- c++ - 无论里面是什么,如何取向量的平均值?
- java - joda.time.DateTime.toLocalDateTime() NoSuchMethodError
- java - Gradle 在运行“./gradlew shadowJar”时找不到 Java
- kdb - KDB:如何将字符串数据类型分配给所有列
- python - 使用预训练的 Word2Vec 模型进行情感分析
- amazon-ec2 - Spot 实例中断多长时间