标签:foreach protect turn padding each mod base add 用户
用户模型
public function show(Post $post,LogManager $log)
{
$post->load("comments"); //这种方式是预加载 ,如果没有这句,就是下面在模板加载的时候才进行模型查询
return view("post.show",compact(‘post‘));
}
post模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
protected $table = "posts";
public $primaryKey = ‘id‘;
public function user()
{
return $this->belongsTo("App\Models\User","user_id",‘id‘);
}
public function comments()
{
return $this->hasMany(‘App\Models\Comment‘,‘post_id‘,‘id‘)->orderBy("created_at",‘desc‘);
}
}
comment模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = ‘comments‘;
public $primaryKey = ‘id‘;
public function post()
{
return $this->belongsTo("App\Models\Post",‘post_id‘,‘id‘);
}
public function user()
{
return $this->belongsTo("App\Models\User",‘user_id‘,‘id‘);
}
}
最后 文章模型 想获取评论和评论用户
查找到post对象
@if(!empty($post->comments))
@foreach($post->comments as $item)
<ul class="list-group" style="padding-bottom:10px;">
<li class="list-group-item">
<h5>{{ $post->created_at }} by {{ $item->user->name }}</h5>
<div>
{{ $item->content }}
</div>
</li>
</ul>
@endforeach
@endif
标签:foreach protect turn padding each mod base add 用户
原文地址:https://www.cnblogs.com/php-linux/p/11689009.html