Php Laravel 5.8:MorphMany关系返回空
评论模式:Php Laravel 5.8:MorphMany关系返回空,php,laravel,laravel-5,eloquent,relationship,Php,Laravel,Laravel 5,Eloquent,Relationship,评论模式: Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('parent_id')->unsigned()->default(0); $
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned()->default(0);
$table->boolean('approved')->default(0);
$table->text('comment');
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->timestamps();
});
公共函数可注释()
{
返回$this->morphTo();
}
公共职能评论()
{
返回$this->hasMany(Comment::class,'parent_id','id');
}
公共函数setCommentAttribute($value)
{
$this->attributes['comment']=str_replace(PHP_EOL,“
”,$value);
}
发布模型:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned()->default(0);
$table->boolean('approved')->default(0);
$table->text('comment');
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->timestamps();
});
公共功能注释()
{
返回$this->morphMany(Comment::class,'commentable');
}
和控制器:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned()->default(0);
$table->boolean('approved')->default(0);
$table->text('comment');
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->timestamps();
});
public function show_注释(Post$Post)
{
$comments=$post->comments()
->其中(“批准”,1)
->其中('parent_id',0)
->最新
->使用(['comments'=>函数($query){
$query->where('approved',1)->latest();
}])->get();
dd(评论);
返回视图('post',compact('comments'));
}
数据库表注释:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned()->default(0);
$table->boolean('approved')->default(0);
$table->text('comment');
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->timestamps();
});
$dd($comments)
返回#项:[]
或为空。有数据库记录,我可以用其他方法访问它们
在询问之前,我做了很多搜索,但没有运气。我花了几个小时试图解决同一问题。对于正在搜索答案的任何人: 检查
comments
表中的commentable\u type
字段是否具有格式正确的路由字符串
'commentable_type'=>'App/Models/Comment',//不起作用
'commentable_type'=>'App\Models\Comment',//Works您能添加与关系相关的表字段和发布的代码吗?@dparoli当然,添加了。您的代码对我来说很好,请尝试删除->where('parent_id',0),然后看看您得到了什么。或者更好地调试您的查询,只需附加->toSql()而不是->get()。您能在注释表中向我们显示一条记录吗?您的可注释类型可能不正确。另外,将外键添加到您的parent\u id
中并使其null
可能是明智的。如何保存模型?如何获取模型?请共享代码?