Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用SQL查询进行简单的变量转换?-拉维尔_Php_Laravel - Fatal编程技术网

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();
  }
}