dongwen2162 2015-01-27 17:24
浏览 263
已采纳

Laravel查询构建器返回对象或数组?

I'm building a very simple web app with Laravel.

I've built two separate Controllers, which each return two separate views, as follows:

ProfileController:

class ProfileController extends BaseController {

    public function user($name)
    {
        $user = User::where('name', '=', $name);

        if ($user->count())
        {
            $user = $user->first();
            $workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();

            Return View::make('profile')
                    ->with('user', $user)
                    ->with('workout', $workout);
        }

        return App::abort(404);
    }
}

WorkoutController:

class WorkoutController extends BaseController {

    public function workout($name)
    {
        $workout = DB::table('workouts')->where('name', '=', $name)->first();

        if ($workout)
        {
            Return View::make('add-exercise')
                    ->with('workout', $workout);
        }

        return App::abort(404);
    }
}

What is confusing me is what I had to do in order to pass a single workout object to each view. As you might have noticed the query builders for workout are different:

$workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();

and

$workout = DB::table('workouts')->where('name', '=', $name)->first();

On the profile view, I get an object using the ->get(); method, but on the add-exercise view, I must use ->first(); or I will otherwise get an array with only one index, where I can then access the object, i.e. $workout[0]->name instead of $workout->name.

Why is this? Shouldn't I be able to use either get and/or first in both controllers and expect the same type of result from both since I want the same thing from the same table?

  • 写回答

1条回答 默认 最新

  • duansanzi5265 2015-01-27 17:34
    关注

    get() returns a collection of objects every time. That collection may have 0 or more objects in it, depending on the results of the query.

    first() calls get() under the hood, but instead of returning the collection of results, it returns the first entry in the collection (if there is one).

    Which method you use depends on what you need. Do you need the collection of all the results (use get()), or do you just want the first result in the collection (use first())?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上