Php 使用SQL查询进行简单的变量转换?-拉维尔
我希望能够通过Php 使用SQL查询进行简单的变量转换?-拉维尔,php,laravel,Php,Laravel,我希望能够通过setUserIdAttributemutator设置user\u id,但它不起作用。当我注释掉mutator时,代码运行良好。下面是我的代码和产生的QueryException错误。请帮忙 // EventController.php public function store(Request $request) { Event::create([ 'name'=>'myName', 'user_id'=>'1' ]);
setUserIdAttribute
mutator设置user\u id
,但它不起作用。当我注释掉mutator时,代码运行良好。下面是我的代码和产生的QueryException错误。请帮忙
// EventController.php
public function store(Request $request)
{
Event::create([
'name'=>'myName',
'user_id'=>'1'
]);
return 'Success!';
}
我认为
$this->attributes['attribute\u name']
是变异的正确方式
// Event.php
class Event extends Model
{
protected $fillable = ['name', 'user_id'];
// It works as expected if I comment this out.
public function setUserIdAttribute($value)
{
// Set Attribute's value.
$this->attributes['user_id'] = Auth::id();
}
}
谢谢!我试试看它是否管用。实际上,我打算使用
Auth::id()
,但我知道这与错误无关,所以我简化了操作。它成功了!请随意编辑您的答案,将Auth::id()
作为一个好的用例。
// The migration file
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
// The error I get
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `events` (`name`, `updated_at`, `created_at`) values (myName, 2017-04-23 22:28:31, 2017-04-23 22:28:31))
// Event.php
class Event extends Model
{
protected $fillable = ['name', 'user_id'];
// It works as expected if I comment this out.
public function setUserIdAttribute($value)
{
// Set Attribute's value.
$this->attributes['user_id'] = Auth::id();
}
}