我目前正在尝试发表评论回复(多语),但我不断收到错误消息:
BadMethodCallException调用未定义的方法Illuminate \ Database \ Query \ Builder :: 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');
});
}
您associate
以错误的方式调用该方法。children_comments()
您在此处调用的方法在任何地方都不存在:
$comment->children_comments()->associate($comments);
要将aComments
与a关联,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();
我认为这将使它更具可读性
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句