【发布时间】:2014-01-03 12:30:49
【问题描述】:
所以,我正在尝试遍历并检查我喜欢查找表中的帖子 ID 与存储在帖子表中的 ID。但我根本没有得到任何回报。我现在完全不知道出了什么问题。
posts.blade.php
<div class="posts">
@foreach(Post::orderBy('created_at', 'DSC')->get() as $post)
<div class="col-md-8" style="background-color: #fff; margin: 10px;">
<center><h2> {{ $post->title }} </h2></center>
<textarea class="form-control" readonly="true" style="cursor: text; width: 500px; padding: 10px;"> {{$post->body }}</textarea>
<div>
Posted by user: {{ $post->user->username }}
</div>
<div>
Total Likes: {{ $post->likes()->count() }}
@foreach(Like::where('post_id', '>', $post->post_id) as $l)
<li> {{ $l->user()->username }} </li>
@endforeach
</div>
</div>
@endforeach
</div>
Like.php 模型
<?php
class Like extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'likes';
protected $fillable = array('user_id', 'post_id');
public $timestamps = false;
public function user()
{
return $this->belongsTo('User');
}
public function post()
{
return $this->belongsTo('Post');
}
}
?>
Post.php 模型
<?php
class Post extends Eloquent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'posts';
protected $fillable = array('user_id', 'title', 'body', 'type');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array();
public function user()
{
return $this->belongsTo('User');
}
public function likes()
{
return $this->hasMany('Like');
}
}
【问题讨论】:
-
在您的视图中这样做被认为是不好的做法...视图不应该知道您的业务逻辑,这应该已经由您的存储库/模型完成并由您的控制器传递给视图。
标签: php laravel laravel-4 eloquent blade