Laravel使用查询显示表记录 [英] Laravel display table record using query

查看:86
本文介绍了Laravel使用查询显示表记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我被困住了.

This may be a silly question but I'm stuck..

我基本上想在laravel中运行一个简单的选择查询,并在数据库结果的单行中显示结果.

I basically want to run a simple select query in laravel and show result from a single row in database result.

我是php和laravel的新手,因此尝试在其中使用模型来挂起MVC.

I'm new to php and laravel so trying to use model in this to get hang on MVC.

以下是我所做的. 路线

Following is what I have done. Route

Route::get('groupprofile/(:any)',array('uses'=>'groups@profile'));

控制器-groups.php

Controller - groups.php

class Groups_Controller extends Base_Controller {
    public $restful=true;
    public function get_profile($groupName){
        $groups=new Groups();
        $groupInfo=$groups->getGroupInfo($groupName);
        return View::make('groups.profile.groupprofile')->with('groupInfo',$groupInfo);
    }
}

模型-groups.php

Model - groups.php

class Groups{
    public function getGroupInfo($name){
        return DB::query('select * from Groups where name=?',array($name));
    }
}

查看-groupprofile.blade.php

View - groupprofile.blade.php

@layout('layouts.default')
@section('content')
<h1>This is a profile page for a group.</h1>
@foreach ($groupInfo -> results as $info)
    <br />Here I want to display all columns e.g. name, philosophy, founder name etc.
    <br />$info->Description
@endforeach
<br />Testing end

@endsection

有人可以指导我该怎么做吗? 我无法理解如何使用Blade在视图中显示传递的结果集中的数据.

Can someone please guide me how should I do this? I'm not able to understand how to display data from passed result set in view using blade.

或者我的方法做错了吗?我在编写查询时比较自在,因此不要使用口才或流利的查询生成器.

Or is my approach wrong to do this? I'm more comfortable in writing queries so not using Eloquent or fluent query builder.

推荐答案

在Larvel中使用Eloquent,这是ORM. 文档对此非常有用.

Look at using Eloquent in Larvel, it's the ORM. The docs are very good about this.

您的模型应为Group.php

Your model should be Group.php

<?php class Group extends Eloquent {}

就是这样!由于我们正在扩展Eloquent,因此我们现在可以像这样拉出一行.

That's it! Since we are extending Eloquent, we can now in our view pull a single row like this.

Group::where('name', '=', $somevar)->first()

当然,您可能希望将其存储在控制器的变量中,然后将对象传递给视图.

Of course, you'll probably want to store that in a variable in your controller and pass the object to your view.

class Groups_Controller extends Base_Controller {
    public $restful=true;
    public function get_profile($groupName){
        $groupInfo = Group::where('name', '=', $groupName)->first()
        return View::make('groups.profile.groupprofile')->with('groupInfo',$groupInfo);
    }
}

然后,在您的视图中,您可以像这样访问该行的属性(MySQL列).

Then in your view, you can access the properties (MySQL columns) of that row like this.

$groupInfo->name

这篇关于Laravel使用查询显示表记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆