因此,我试图为用户创建一个功能,以便在创建帖子时添加多个类别。
这是一个字符串被传递到控制器的例子:
$request['categories'] = "Sports, Football, Finals";
- 我需要做的第一件事是拆分字符串,清理它从空白处创建一个数组
- 然后检查每个类别(如果存在),否则创建一个新类别。Laravel-firstOrCreate()方法可能非常适合这种情况
- 最后,能够为每个帖子关联多个类别
这就是我目前所拥有的:
片剂
张贴
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->text('body');
$table->integer('user_id');
});
类别
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
});
类别_后
Schema::create('category_post', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
});
型号
后
class Post extends Model
{
public function categories()
{
return $this->hasMany('AppCategory');
}
}
类别
class Category extends Model
{
public function post()
{
return $this->belongsToMany('AppPost');
}
}
我不知道我是否正确设置了表格,是否建立了正确的模型关系,我对如何设置控制器感到一无所知。
我从这些帖子中得到了一些灵感:
- 如何在laravel中插入多类别和多列不同类别的帖子
- https://laracasts.com/discuss/channels/general-discussion/eloquent-attach-method-for-multiple-inserts-into-a-pivot-table
首先,在多对多Eloquent关系中,必须在两个模型中都使用belongsToMany
函数,因此更改Post
模型如下:
public function categories()
{
return $this->belongsToMany('AppCategory');
}
此外,将Category
型号中的post
函数重命名为posts
,并将protected $fillable = ['name'];
添加到Category
型号中
最后,对于控制器方法,您可以使用以下代码:
$categoryStr = $request->input('categories');
$categories = array_map('trim', explode(',', $categoryStr));
foreach ($categories as $category) {
$catModel = AppCategory::firstOrCreate(['name' => $category]);
$catModel->posts()->save($post); //$post can be the post model that you want to associate with the category
}