我目前正试图做出评论回复(线程-ish),我一直收到一个错误的回复:
对未定义方法Illuminate\Database\Query\Builder::children_comments()的BadMethodCallException调用
以下是我的方法:
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');
});
}发布于 2015-11-27 12:56:59
您正在错误地调用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();我认为这会使它更易读懂。
https://stackoverflow.com/questions/33957894
复制相似问题