我对使用larateJoin的laravel select有问题。我正在尝试选择2个帖子并计算有多少评论(第一个帖子有7条评论,第二个-0),但我只有第一条有7条评论。
代码是:
$posts = DB::table('posts')
->leftJoin('comments', 'comments.post', '=', 'posts.id')
->select(DB::raw('posts.title, posts.body, posts.created_at, posts.slug, CASE WHEN comments.post IS NULL THEN 0 WHEN comments.post IS NOT NULL THEN count(comments.post) END as count'))
->get();
当我尝试检查在网络浏览器中看到的内容时,出现错误:
Call to a member function count() on a non-object
我在使用
@if($posts->count())
的行的视图文件中出现此错误我已调试使用
print_r()
仅收到一则帖子。有什么建议么?
最佳答案
我认为您最好的选择是使用laravel的Eloquent ORM的某些内置功能。
在模型中建立关系:
Post.php:
<?php
class Post extends Eloquent {
protected $table = 'posts';
public function comments()
{
return $this->hasMany('Comment', 'posts');//first param refrences the other model, second is the foreign key
}
Comment.php:
<?php
class Comment extends Eloquent {
protected $table = 'comments';
public function comments()
{
return $this->belongsTo('Post');//first param refrences the other model, second is unnecessary if you are using auto incrementing id
}
现在,您已经建立了关系,并且不需要加入。
用法:
也许有更好的方法可以做到这一点,但这应该可行。
$posts = Post::with('comments')->get();//retrieves all posts with comments
foreach($posts as $post){
$count = count($post['comments']);
$post['comment_count'] = $count;
}
return $posts;
这将返回一个包含所有帖子的结果,一个名为“ comments”的字段包含一个包含所有相关评论的数组。 “ comment_count”字段将包含计数。
例:
[
{
"id": 1,
"created_at": "2014-07-02 11:34:00",
"updated_at": "2014-07-02 11:34:00",
"post_title": "hello there",
"comment_count": 1,
"comments": [
{
"id":'blah'
"comment_title":"blah"
}
]
}
您现在可以将此传递到您的视图并遍历每个帖子并获取
$post['comment_count']
关于php - Laravel离开Join无法正确返回,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24558648/