0

我已经有一段时间了,我想做的是从选择框中获取所选值的 id。使用这个片段,它没有得到 id,我想知道为什么。我很困惑什么可能是错的

此代码用于获取所选值的 id:

private static function compareCompany(ProductRequest $productRequest){
            $companyPicked = $productRequest->companyname;
            $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
            $companies = new Company;
            if($companies->user_id === Auth::user()->id)
            {   
                foreach($listedCompanies as $company) {
                    if($company->companyname === $companyPicked)
                    {
                        return $company->id;
                    } 
                }
            }
        }

这是使用为公司返回的 id 创建新产品

public function store(ProductRequest $productRequest)
    {
       $product = new Product;
        $company = new Company;
       if($productRequest->isMethod('post')){

       $product->user_id     = Auth::user()->id;
       $product->company_id  = $this->compareCompany($productRequest);
       $product->companyname = $productRequest->companyname;
       $product->productname = $productRequest->productname;

       $product->save();
       return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
       }else{
            return redirect('company-create')->withErrors($productRequest)->withInput();
        }
    }

这是视图:

<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>

这是用于将返回值绑定到视图的代码:

public function create()
    {

      $listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'companyname')->toArray();
        return view('product.create')
        ->with('listCompanies', $listCompanies);
    }
4

2 回答 2

0

Change ->lists('companyname', 'companyname') to ->lists('companyname', 'id')

It will return the id of the table of Company model.

于 2015-12-29T20:34:18.580 回答
0

我怀疑问题出在你的compareCompany方法上。那里有几个问题。

这是您的代码(稍微清理一下):

private static function compareCompany(ProductRequest $productRequest)
{
    $companyPicked = $productRequest->companyname;

    $listedCompanies = Company::where('user_id', '=', Auth::user()->id);

    $companies = new Company;

    if($companies->user_id === Auth::user()->id)
    {   
        foreach($listedCompanies as $company) {
            if($company->companyname === $companyPicked)
            {
                return $company->id;
            } 
        }
    }
}

以下是问题:

  1. $listedCompanies = Company::where('user_id', '=', Auth::user()->id);

    该声明实际上并未产生公司名单。您需要->get()在最后添加,如下所示:

$listedCompanies = Company::where('user_id', '=', Auth::user()->id)->get();

  1. $companies = new Company;

    Company这会创建一个新的、未初始化的模型实例。在下一行,您继续检查该user_id实例的属性,但它没有设置任何内容,因为它是全新的。所以第一个if()语句总是失败。目前尚不清楚您要在这里做什么,所以我不确定如何解决这个问题。我的猜测是你试图只过滤掉属于当前用户的公司,但你已经用你的 完成了Company::where(...)->get(),所以这不是必需的。

于 2015-12-29T16:29:03.843 回答