我正在做一个 Laravel-5.4 项目。我有三个表users,articles并且comments在我的数据库中。
articles表格截图:
comments表格截图:
Article 模型:
class Article extends Model
{
public function comments() {
return $this->morphMany('App\Comment', 'commentable');
}
}
Run Code Online (Sandbox Code Playgroud)
Comment 模型:
class Comment extends Model
{
public function commentable() {
return $this->morphTo();
}
}
Run Code Online (Sandbox Code Playgroud)
ArticleController 包含以下方法:
public function showComments() {
return Article::find(1)->comments;
}
Run Code Online (Sandbox Code Playgroud)
以上showComments()方法返回[](空数组)。我想返回这篇文章的所有评论id=1。问题是什么?
小智 6
该commentable_type列应存储完全命名空间的模型名称,例如App\User. 您是否手动输入了这些信息?尝试将其更改为App\User,App\Article等等,看看是否能工程。
您可以morphMap在您的引导方法中创建一个将AppServiceProvider这些命名空间别名为更具描述性的名称,就像您在此处所做的那样。
public function boot()
{
Relation::morphMap([
'User' => 'App\User',
// etc
]);
}
Run Code Online (Sandbox Code Playgroud)
导入Relation:
use Illuminate\Database\Eloquent\Relations\Relation;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |