【发布时间】:2015-10-27 12:46:18
【问题描述】:
我正在使用 Laravel 5。我一直在关注 this tutorial 关于使用表单创建带有“标签”的文章。我已经用类别替换了标签。我的文章“属于许多”类别,而我的类别“属于许多”文章。我有一个创建新文章的表单,但它只在articles 表中创建一个条目,而不是在article_category 数据透视表中。
我收到此错误:
FatalErrorException in ArticlesController.php line 77:
调用数组上的成员函数 categories()
我认为问题出在store 函数的第四行。我找不到有同样问题的人。该行应该将文章id 附加到ids 类别,但它不起作用。感谢您的帮助。
我的文章控制器:
public function store(CreateArticleRequest $request)
{
$article = $request->all();
Article::create($article);
$categoriesId = $request->input('categories');
$article->categories()->attach($categoriesId);
return redirect()->route('articles_path');
}
命名空间:
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\CreateArticleRequest;
use App\Http\Controllers\Controller;
use App\Category;
use App\Day;
路线:
Route::resource('articles', 'ArticlesController', [
'names' => [
'index' => 'articles_path',
'show' => 'article_path',
'edit' => 'articleEdit_path',
'update' => 'articleUpdate_path',
'create' => 'articleCreate_path',
'store' => 'articleStore_path'
]
]);
文章型号:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category', 'article_category', 'category_id', 'article_id')->withTimestamps();
}
protected $fillable = array('title', 'description', 'image', 'lat', 'lng');
}
类别模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article', 'article_category', 'article_id', 'category_id')->withTimestamps();
}
protected $fillable = array('name');
}
数据透视表:
Schema::create('article_category', function (Blueprint $table) {
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
【问题讨论】: