Laravel从存储对象获取id

时间:2015-06-10 12:27:42

标签: php mysql laravel eloquent

我有一个公司表和一个包含各种值的属性表。

一家公司拥有多个属性,一个属性属于公司。

现在我在属性表中有一个带有'account_nr_start'的值(例如,当一个新用户被添加到公司时,其account_id从1000开始计数)。

假设我创建了一个新的Company[id=5]account_nr_start 1101(参考编号),请输入:enter image description here

但是它没有上传没有company_id的规则,这很清楚,因为当我创建一个新公司时它没有要获得的company_id,但是如何在商店函数中获取ID以便它仍然可以将它发送到属性表?

enter image description here

控制器:

public function __construct(Company $company, User $user)
{
    if(Auth::user()->usertype_id == 7)
    {
        $this->company = $company;
    }
    else
    {
        $this->company_id = Auth::user()->company_id;
        $this->company  = $company->Where(function($query)
        {
            $query->where('id', '=', $this->company_id )
                ->orWhere('parent_id','=', $this->company_id);
        }) ;
    }

    $this->user = $user;

    $this->middleware('auth');

    $page_title = trans('common.companies');
    view()->share('page_title', $page_title);
}


public function create(Company $company, CompaniesController $companies)
{
    $companies = $companies->getCompaniesName(Auth::user()->company_id);

    return view('company.create', ['company' => $company, 'id' => 'edit', 'companies' => $companies]);
}


public function store(CreateCompanyRequest $request, Company $company, Attribute $attribute)
{
    $company->create($request->all());

    dd($company->id);

    $attribute->create($request->only('company_id', 'attribute_nr', 'value'));

    return redirect()->route('company.index');
}

我试着dd($company->id); but that doesn't work, result will be null`

1 个答案:

答案 0 :(得分:1)

要获取已创建对象的id,您应该运行:

$company = $company->create($request->all());

dd($company->id);

而不是

$company->create($request->all());

dd($company->id);

现在,您可以通过以下方式创建Attribute时传递公司ID:

$attribute->create(array_merge($request->only('attribute_nr', 'value'), ['company_id' => $company->id]);