1
我正在创建一个论坛,用户可以在该论坛中创建主题并留下回复,就像本论坛一样。无法在评论表中添加topic_id
我做了一个像下面的关系。但是,当我保存一篇文章topic_id没有被连接。我认为saveReply方法是错误的。
另外,在这种情况下,您如何将特定帖子的评论传递给show方法中的视图?
我是一个noob,所以如果我的问题含糊不清,但任何帮助将不胜感激!
路线
Route::group(['middleware' => 'web'], function() {
Route::get('forums','[email protected]');
Route::get('forums/create','[email protected]');
Route::post('forums', '[email protected]');
Route::get('forums/{category_id}/{title}','[email protected]');
Route::post('forums/{category_id}/{title}', '[email protected]');
});
forumcontroller
class ForumsController extends Controller
{
public function index()
{
\t $categories = Category::all();
\t $topics = Topic::latest()->get();
return view('forums.index',compact('categories','topics'));
}
public function create()
{
$categories = Category::lists('title', 'id');
return view('forums.create', compact('categories'));
}
public function store(Request $request)
{
Auth::user()->topics()->save(new Topic($request->all()));
flash()->success('投稿しました','success');
return redirect('forums');
}
public function show($category_id, $title)
{
Topic::where(compact('category_id','title'))->first();
return view('forums.post', compact('topic'));
}
public function saveReply (Request $request)
{
Auth::user()->comments()->save(new Comment($category_id,$request->all()));
flash()->success('投稿しました','success');
return redirect()->back();
}
}
主题模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class topic extends Model
{
protected $fillable = [
\t 'title',
\t 'body',
'category_id'
\t ];
public function category()
{
return $this->belongsTo('App\category');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
用户模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function articles()
{
return $this->hasMany('App\Article');
}
public function topics()
{
return $this->hasMany('App\Topic');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
评论模型
class Comment extends Model
{
\t protected $fillable = [
\t \t \t 'reply',
\t \t \t 'user_id',
\t \t \t 'topic_id'
\t \t ];
public function topic()
{
return $this->belongsTo('App\Topic');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
评语表
class CreateCommentsTable extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->text('reply');
$table->integer('user_id')->unsigned();
$table->integer('topic_id')->unsigned();
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
}