【发布时间】:2016-09-15 18:43:25
【问题描述】:
我正在尝试以雄辩的关系保存数据。
我有以下三个表:用户表、类别表和帖子表。
张贴表
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->string('heading');
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('user_id')->references('id')->on('users');
});
关系:
类别:
public function posts() {
return $this->hasMany('App\Post');
}
帖子:
public function user() {
return $this->belongsTo('App\User');
}
public function category() {
return $this->belongsTo('App\Category');
}
用户:
public function posts($category) {
return $this->hasMany('App\Post');
}
我的问题是,我怎样才能通过在创建函数中传递标题来保存帖子。我想使用这种关系。作为一个例子,我想使用这种代码:
$data = ['heading' => $heading];
$user->posts()->category()->create($data);
有可能做这种事情吗?
或任何其他简单的方法来实现这一点。
编辑
我需要使用这种关系来创建帖子。
按照流程:
用户将填写表格,我将从中获取数据 类别 ID。
现在我需要为该用户创建与给定类别 ID 相关的数据。
【问题讨论】:
标签: mysql laravel eloquent laravel-5.2