【发布时间】:2016-08-27 13:23:07
【问题描述】:
我有标签和帖子模型。
迁移标签
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('post_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamp();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tags');
schema::drop('post_tag');
}
}
迁移帖
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('body');
$table->text('filename');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
应用\标签
class Tag extends Model
{
protected $table="tags";
public $timestamps = true;
protected $fillable = ['name'];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* Many to Many relations make with post
*/
public function posts()
{
return $this->belongsToMany('App\Post','post_tag','post_id');
}
}
应用\发布
class Post extends Model
{
protected $table="posts";
public $timestamps = true;
protected $fillable = ['title', 'body', 'filename'];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* one to many relationship with user
*/
public function user()
{
return $this->belongsTo('App\User','user_id');
}
/**
* @return BelongsToMany relationship with tags
*
*/
public function tags()
{
return $this->belongsToMany('App\Tag','post_tag','tag_id')->withTimestamps();
}
}
我想附加帖子和标签。有创建帖子表单,我想要这个表单附加标签。我会怎么做?
PostController@store
public function store(Request $request)
{
\Auth::user()->posts()->save(new Post($request->all()));
return \Redirect::route('posts.index');
}
我在 Laravel 文档中找到但我不使用方法
App\User::find(1)->roles()->save($role, ['expires' => $expires]);
【问题讨论】:
-
这有点令人困惑,您能否进一步澄清一下?您展示了您的
Post和Tag模型,但看起来您将Post附加到您的User,然后将Role附加到您的User。不清楚你到底在问什么。 -
你是对的。我编辑这个问题
-
我已编辑。我想附上帖子和标签
-
我相信您应该将附加用于多对多关系。查看文档以获取更多信息:laravel.com/docs/5.2/…
标签: php laravel laravel-5 many-to-many has-and-belongs-to-many