用户模型
public function show(Post $post,LogManager $log)
{
$post->load("comments"); //这种方式是预加载 ,如果没有这句,就是下面在模板加载的时候才进行模型查询
return view("post.show",compact('post'));
}
post模型
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
//
protected $table = "posts";
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo("AppModelsUser","user_id",'id');
}
public function comments()
{
return $this->hasMany('AppModelsComment','post_id','id')->orderBy("created_at",'desc');
}
}
comment模型
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Comment extends Model
{
protected $table = 'comments';
public $primaryKey = 'id';
public function post()
{
return $this->belongsTo("AppModelsPost",'post_id','id');
}
public function user()
{
return $this->belongsTo("AppModelsUser",'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