不使用foreach将单个结果存储到变量中

时间:2018-02-17 15:03:47

标签: laravel eloquent

我想将数据库中的单个结果存储到变量中。我尝试过不同的方式,但并没有真正得到我想要的东西。请参阅下面的代码:这是在控制器中

public function create()
{
    //
    $user_id = Auth::id();

    $company_id = User::select('company_id')->where('id', $user_id)->first();

    $curriculums = Curriculum::where('company_id','=', $company_id)->get();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>$user_id]);
}

dd的结果是:

  

收藏{#2232▼     #it​​ems:[]   }

如果我用实际ID替换$ curriculum_id,我会得到正确的结果。所以我认为这是因为即使我把$company_id = User::select('company_id')->where('id', $user_id)->first();放在最后,->first()也没有真正返回单个值。请帮助。我是laravel的新手

1 个答案:

答案 0 :(得分:4)

你需要做一些修改:

public function create()
{
    //
    $user_id = Auth::id();
// it return user not value
    $user = User::select('company_id')->where('id', $user_id)->first();   
// $user->company_id not $user
    $curriculums = Curriculum::where('company_id','=', $user->company_id)->first();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>$user_id]);
}

编辑:您还可以做另外的事情:

public function create()
{
    //get company_id 
    $company_id = Auth::user()->company_id;

    $curriculums = Curriculum::where('company_id','=', $company_id)->first();
    dd($curriculums);


    return view('qualificationheaders.create', ['user_id'=>Auth::id()]);
}