laravel - 视图没有返回存储在数据库中的属性
问题描述
我正在尝试返回哪个用户发表了评论,以及他们发表评论的时间。
我有评论模型
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $guarded = [];
public function adjustments()
{
return $this->belongsToMany(User::class, 'adjustments')
->withTimestamps();
}
}
跟踪哪些用户发布了哪些评论的数据透视表
public function up()
{
Schema::create('adjustments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->unsignedInteger('comments_id')->index();
$table->timestamps();
});
}
一个空的调整模型
use Illuminate\Database\Eloquent\Model;
class adjustment extends Model
{
//
}
在php artisan tinker
何时$comment = App\comment::first();
,$user = App\user::first();
我能够成功地将 user_id 附加到 comment_id 使用$comment->adjustments()->attach($user->id)
和调用App\adjustments::all();
将正确返回
=> Illuminate\Database\Eloquent\Collection {#2935 all: [ App\adjustment {#2941 id: 1, user_id: 1, comments_id: 1, created_at: "2019-11-16 17:05:10", updated_at: "2019-11-16 17:05:10", }, ], }
当我试图在我的视图中显示调整时,我得到一个空列表。
@foreach ($comment->adjustments as $user)
<li>{{$user->name}} on {{$user->pivot->updated_at}}</li>
@endforeach
在我的产品控制器中(用户对产品发表评论)我的 show 函数中有以下代码
public function show(products $product, comments $comment, User $user)
{
return view ('products.show', compact('product'), compact('comment'));
}
解决方案
在这里,您不需要数据透视表。因为在这里你有一对多的关系。用户可以创建许多评论。& 一个评论属于一个用户。在用户模型中添加这个
public function comments()
{
return $this->hasMany(Comment::class);
}
& 评论表你有一个外键 user_id。
在评论模型中
public function user()
{
return $this->belongsTo(User::class,'user_id','id')
}
public function show(products $product, comments $comment, User $user)
{
$comments=Comment::with('user')->all();
return view ('products.show', compact(['product','comments']));
}
@foreach ($comments as $comment)
<li>{{$comment->user->name}} on {{$comment->updated_at}}</li>
@endforeach
然后您可以使用用户访问所有评论表数据
推荐阅读
- spring - 为什么在类中没有返回 discriminatorColumn dtype
- azure - Azure eventhub 有回调方法吗?
- drake - 在 Drake 中生成和操作多个模型到 iiwa arm MeshCat 仿真中
- reactjs - React 使用 Google 登录未重定向到仪表板
- python - 无限迭代器
- postgresql - Postgres - 将国际原子时间转换为 UTC 时间(在 SQL 函数体中使用 IF 循环)
- sql - 如何按 SDO_GEOMETRY 数据类型分组
- django - 如何使用 save_to_database() 跳过一些在 django-excel 中有错误的行
- c++ - OpenCascade 未定义的函数参考
- tensorflow - 在 Keras 中,ResNet50 有一个奇怪的模式