gpt4 book ai didi

php - Laravel leftJoin 未正确返回

转载 作者:行者123 更新时间:2023-11-29 12:52:09 24 4
gpt4 key购买 nike

我在使用 leftJoin 进行 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();

当我尝试检查我在网络浏览器中看到的内容时,出现错误:调用非对象上的成员函数 count()

我的 View 文件中使用 @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"
}
]

}

您现在可以将其传递到您的 View 并循环浏览每个帖子并获取 $post['comment_count']

关于php - Laravel leftJoin 未正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24558648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com