因此,我正在尝试为用户创建功能,以便在创建帖子时添加多个类别。
这是传递给控制器的字符串示例:
$request['categories'] = "Sports, Football, Finals";
这是我到目前为止所做的:
TABLES
帖子
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');
});
category_post
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('App\Category');
}
}
分类
class Category extends Model
{
public function post()
{
return $this->belongsToMany('App\Post');
}
}
我不知道我是否正确设置了表格,如果我建立了正确的模型关系,我对如何设置控制器 感到无能为力。
我从这些帖子中获得了一些灵感:
答案 0 :(得分:1)
首先,在many to many Eloquent relationships中,您必须在两个模型中使用belongsToMany
函数,因此请更改您的Post
模型:
public function categories()
{
return $this->belongsToMany('App\Category');
}
此外,将post
模型中的Category
功能重命名为posts
,并将protected $fillable = ['name'];
添加到Category
型号
最后,对于控制器方法,您可以使用以下代码:
$categoryStr = $request->input('categories');
$categories = array_map('trim', explode(',', $categoryStr));
foreach ($categories as $category) {
$catModel = App\Category::firstOrCreate(['name' => $category]);
$catModel->posts()->save($post); //$post can be the post model that you want to associate with the category
}