我在做一个Laravel-5.4项目。我的数据库中有三个表users、articles和comments。
articles表的屏幕截图:

comments表的屏幕截图:

Article模型:
class Article extends Model
{
public function comments() {
return $this->morphMany('App\Comment', 'commentable');
}
}Comment模型:
class Comment extends Model
{
public function commentable() {
return $this->morphTo();
}
}ArticleController包含以下方法:
public function showComments() {
return Article::find(1)->comments;
}上面的showComments()方法返回[] (空数组)。我想返回文章的所有评论,其中有id=1。有什么问题吗?
发布于 2018-11-05 12:51:12
commentable_type列应该存储完全命名空间的模型名称,例如App\User。你手动输入了这个信息吗?尝试将其更改为App\User、App\Article等,看看是否有效。
您可以在您的morphMap的引导方法中创建一个AppServiceProvider,以便将这些命名空间别名为更具描述性的名称,就像在这里所做的那样。
public function boot()
{
Relation::morphMap([
'User' => 'App\User',
// etc
]);
}导入Relation
use Illuminate\Database\Eloquent\Relations\Relation;https://stackoverflow.com/questions/53154708
复制相似问题