雄辩的声明在foreach(Laravel 4)

时间:2013-12-16 07:25:20

标签: php laravel laravel-4 eloquent blade

所以,我正在尝试迭代并检查我喜欢的查找表中的帖子ID到存储在posts表中的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');
    }

}

2 个答案:

答案 0 :(得分:2)

关于您的查询,我认为您有两个错误:

  1. 您需要在get()
  2. 之后追加where($condition)
  3. 您正在查询的邮件ID大于您的帖子ID。不应该是一个等号吗?
  4. 它应该是这样的:

    $likes = Like::where('post_id', '=', $post->post_id)->get();
    

    然后,正如我在评论中指出的那样,我建议您在存储库类中执行所有与模型相关的内容,在控制器中使用该类,并将结果传递给视图。

    您的存储库类:

    class PostRepository {
    
        public function byDate()
        {
            // return posts by date
        }
    
    }
    

    你的控制器:

    class MyAwesomeController {
    
        protected $postRepository;
    
        ...
    
        public function awesomeSection()
        {
            $posts = $this->postRepository->byDate();
    
            return View::make('awesome.view')->with('posts' => $posts);
            // or
            return View::make('awesome.view', compact('posts'));
        }
    

    }


    进一步阅读:

答案 1 :(得分:1)

在您的视图中避免您的业务逻辑。如果您的应用程序很小,您可以在控制器中执行Manuel所说的。

但是,在您的代码中缺少get()方法。希望这能解决问题。

        @foreach(Like::where('post_id', '>', $post->post_id)->get() as $l)
            <li> {{ $l->user()->username }} </li>
        @endforeach