如何在视图中打印sql计数?

时间:2015-11-19 13:17:49

标签: php mysql laravel

我有这个

$noOfcomment = DB::select("SELECT COUNT(comment) as cs FROM comments WHERE placeid='$pid->placeid'"); 

但我不知道如何在视图中打印结果?

2 个答案:

答案 0 :(得分:2)

  

select方法将始终返回array个结果。

print_r($noOfcomment);

打印计数:

echo $noOfcomment[0]->cs;

要在视图中打印结果,您必须传递变量:

return View::make('viewName', array('count' => $noOfcomment[0]->cs));

然后在您的视图中打印结果:

<?php echo $count; ?>

要使用Laravel获取有关数据库的更多详细信息,请检查:

http://laravel.com/docs/4.2/database

要了解有关Laravel中视图的更多详细信息,请查看:

http://laravel.com/docs/4.2/responses

答案 1 :(得分:0)

我建议使用Laravel Eloquent aggregate函数代替使用DB facade

namespace CC.Plugin.MyPlugin.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<CC.Data.CcDataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(CC.Data.CcDataContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

将数据传递到视图

$noOfcomments = Comment::where('placeid', your id here)->count();

return view('viewname', compact('noOfcomments'));// and echo $noOfcomments variable in your view 方法返回一个数组而你选择一个特定的列时,我假设你可以访问计数变量,如

SELECT

<强>更新

在进行投票之前,请先评论一下这个问题。