1
我正在使用Laravel 5.我一直在關注使用表格創建帶有'tags'的文章的this tutorial。我用類別替換了標籤。我的文章'屬於很多'類別,我的類別'屬於許多'文章。我有一個表單來創建一篇新文章,但它僅在articles
表中創建條目,而不是在article_category
數據透視表中創建條目。爲什麼我的表單不能發佈到數據透視表?
我得到這個錯誤:
FatalErrorException in ArticlesController.php line 77:
調用一個成員函數類別()在陣列
我認爲這個問題是在store
功能第四行。我找不到有同樣問題的人。該行應該將文章id
附加到類別ids
,但它不起作用。感謝任何幫助。
我ArticlesController:
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();
});
嗨,謝謝。如果我改變,我得到這個錯誤:SQLSTATE [23000]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗('storelocatordb'.'article_category',CONSTRAINT'article_category_category_id_foreign' FOREIGN KEY('category_id ('id'))(SQL:insert into'article_category'('article_id','category_id','created_at','updated_at')values(1,48,2015-10-27 20: 11:10,2015-10-27 20:11:10),(2,48,2015-10-27 20:11:10,2015-10-27 20:11:10)) –
看起來像你的類別正在嘗試附加到尚未創建的文章,是否有可能?是否存在48的id類別? –
只有三個類別的id爲1,2,3。 ? –