首页 > 解决方案 > 视图没有返回存储在数据库中的属性

问题描述

我正在尝试返回哪个用户发表了评论,以及他们发表评论的时间。

我有评论模型

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'));
}

标签: laravellaravel-5eloquentlaravel-6

解决方案


在这里,您不需要数据透视表。因为在这里你有一对多的关系。用户可以创建许多评论。& 一个评论属于一个用户。在用户模型中添加这个

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

然后您可以使用用户访问所有评论表数据


推荐阅读