Laravel 新手,抱歉,如果这很明显,但我已经坚持了很长时间!
目标:要使用表单中的完整值批量分配 Quote::create()
数据库插入,加设置当前登录用户的用户 ID。
问题:user_id
列从未写入数据库。每隔一列,但 user_id
保持为 0。
我当然尝试过将 user_id
添加到 $fillable
数组,但我不希望它是用户可填写的 - 我希望它由Laravel 的 Auth::id()
函数。
知道为什么这不会被存储吗?是因为 $quote->create()
函数没有考虑之前设置的数据,只是将其参数作为要保存的所有内容吗?如果是这样,我该怎么做?
这是我的 Controller 的 store()
函数:
/**
* Stores a created quote in the database
*
* @param QuoteRequest $request
*
*/
public function store(QuoteRequest $request)
{
// This method will only get fired if QuoteRequest passes
$quote = new Quote;
$quote->user_id = Auth::id();
$quote->create($request->all());
echo 'Job done';
}
这是我的 Quote
模型:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
class Quote extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'quotes';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'quote_person',
'quote_value',
'quote_date'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [ ];
/*
* Request/User many-to-one relationship
*/
public function user()
{
return $this->belongsTo('App\User');
}
/*
* Belongs to current User scope
*/
public function scopeMine($query)
{
return $query->where('user_id', Auth::id());
}
}
最佳答案
试试这个,看看它是否有效。
public function store(QuoteRequest $request)
{
// This method will only get fired if QuoteRequest passes
$quote = new Quote;
$quote->fill($request->all());
$quote->user_id = Auth::id();
$quote->save();
echo 'Job done';
}
关于php - Laravel 的 Model::create() 函数未设置自定义字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198565/