dongwo7858 2017-04-23 22:43
浏览 32
已采纳

简单的mutator与SQL Query拧紧? - Laravel

I want to be able to set the user_id via the setUserIdAttribute mutator but it won't work. The code works fine when I comment out the mutator. Below is my code and the resulting QueryException error. Please help!

// EventController.php
public function store(Request $request)
{
    Event::create([
      'name'=>'myName',
      'user_id'=>'1'
    ]);
    return 'Success!';
}

// Event.php
class Event extends Model
{
    protected $fillable = ['name', 'user_id'];

    // It works as expected if I comment this out.
    public function setUserIdAttribute($value)
    {
        // I know this code will run. If i do echo 'foo' it works.
        return '1';
    }
}

// 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))
  • 写回答

1条回答 默认 最新

  • duanli6834 2017-04-23 22:57
    关注

    I think $this->attributes['attribute_name'] is the correct way to mutate.

    // 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();
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题