设置此查询的最佳方法是什么?我似乎无法找到有关实际插入或更新的任何文档,我希望通过Eloquent模型来实现,但似乎无法使其正常工作
任何帮助将不胜感激。
DB::table('questions')->insert([
'marital_status' => $request->marital_status,
'job_title' => $request->job_Title,
'industry' => $request->industry,
'occupation' => $request->occupation,
'paye' => $request->paye,
'self_employed' => $request->self_employed,
'child_benefit' => $request->child_benefit,
'work_home' => $request->work_home,
'own_transport' => $request->own_transport,
'company_vehicle' => $request->company_vehicle,
'annual_income' => $request->annual_income,
'pay_memberships' => $request->pay_memberships,
'income_benefits' => $request->income_benefits,
'printer' => $request->printer,
'contact' => $request->contact,
'share' => $request->share,
'terms' => $request->terms,
'user_id' => $user
]);
这是我的问题模型
<?php
namespace App;
class Questions extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
];
public function users(){
return $this->hasOne('App\User');
}
}
答案 0 :(得分:5)
将Eloquent与mass assignment:
一起使用KnownHosts.add
或者:
Question::updateOrCreate($request->all()->put('user_id', $user));
不要忘记用$question = Question::firstOrNew('some_id', $someId);
$question->fill($request->all()->put('user_id', $user))->save();
数组填充您想要保留的所有属性:
$fillable
<强>更新强>
如果class Question extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
]
方法由于某种原因无效,请尝试以下操作:
put()
然后只使用$request->merge(['user_id' => $user]);
或者:
$request->all()
然后使用$requestData = $request->all();
$requestData['user_id'] = $user;