码迷,mamicode.com
首页 > 其他好文 > 详细

laravel模型关联评论

时间:2019-10-16 23:34:17      阅读:93      评论:0      收藏:0      [点我收藏+]

标签: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


laravel模型关联评论

标签:foreach   protect   turn   padding   each   mod   base   add   用户   

原文地址:https://www.cnblogs.com/php-linux/p/11689009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!