我目前正在尝试发表评论回复(Threaded-ish) 我一直收到错误说:
BadMethodCallException调用未定义的方法 照亮\数据库\查询\生成器:: children_comments()
这是我的方法:
public function commentsReply(Requests\CreateCommentsRequest $request, $comment)
{
$comments = Comments::whereId($comment)->first();
$comment = new ChildrenComment(Request::all());
$comment->pubslished_at = Carbon::now();
$comment->user()->associate(Auth::user());
$comment->children_comments()->associate($comments);
$comment->save();
return Redirect::back();
}
这是我的模特:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class ChildrenComment extends Model {
protected $fillable = [
'id',
'user_id',
'post_id',
'parent_id',
'comment'
];
public function setPublishedAtAttribute($date)
{
$this->attributes['pubslished_at'] = Carbon::parse($date);
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->belongsTo('App\Comments');
}
}
如果有必要,这是我的迁移架构:
public function up()
{
Schema::create('children_comments', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->integer('parent_id')->unsigned();
$table->text('comment');
$table->string('fileToUpload')->default("uploads/images/comments/NFF4D00-0.png");
$table->timestamps();;
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('post_id')
->references('id')
->on('posts')
->onDelete('cascade');
$table->foreign('parent_id')
->references('id')
->on('comments')
->onDelete('cascade');
});
}
答案 0 :(得分:1)
您正在以错误的方式调用associate
方法。您在此处调用的方法children_comments()
在任何地方都不存在:
$comment->children_comments()->associate($comments);
要将Comments
与ChildrenComment
相关联,您应该这样做:
$comment->comments()->associate($comments);
最后一点:我发现你将变量命名的方式非常混乱(尤其是因为你使用复数形式表示具有单个值的变量)。我会这样做:
//is't only one comment so 'comment' not 'comments'
$comment = Comments::whereId($comment)->first();
//$childComment is another object, so give it another name
$childComment = new ChildrenComment(Request::all());
$childComment->pubslished_at = Carbon::now();
$childComment->user()->associate(Auth::user());
//this statement represent a relation with one element, so name it 'comment()', not 'comments()'
$childComment->comment()->associate( $comment );
$childComment->save();
我认为这会让它更具可读性