首页 文章

从laravel中的表单输入中将数据插入到hasone表中

提问于
浏览
1

我有两个表一个用户是父母,另一个是帖子(子)表及其库存

public function up(){
        Schema::create('posts', function (Blueprint $table) {

            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->string('body');
            $table->timestamps();

        }
   }

我已经指定了

$this->hasOne('Post');

与用户模型的关系 . 现在我想将数据插入到posts表中,其中表单i可以将数据保存到title和body列中各自的id .

1 回答

  • 0

    如果是经过身份验证的用户,则可以执行以下操作:

    auth()->user()->posts()->create($request->all());
    

    要使 create() 方法工作,您还需要 Post 数组包含 Post 模型中的所有属性:

    $protected fillable = ['title', 'body'];
    

相关问题