视图未返回存储在数据库中的属性

时间:2019-11-16 17:38:34

标签: laravel laravel-5 eloquent laravel-6

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

我有一个评论模型

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();可以使用$comment->adjustments()->attach($user->id)成功地将user_id附加到comment_id上,并调用App\adjustments::all();会正确返回< / p>

=> 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

在我的产品控制器中(用户对产品发表评论),我的显示功能中包含以下代码

public function show(products $product, comments $comment, User $user)
{
    return view ('products.show', compact('product'), compact('comment'));
}

1 个答案:

答案 0 :(得分:2)

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

public function comments()
{
return $this->hasMany(Comment::class);
}

&注释表u具有外键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

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