Laravel eloquent拥有许多模型访问权限
我有以下三种型号: -评论 -有许多评论的项目 -包含许多项的列表&hasManyThrough'comment'、'item' 这意味着我有很多项目的列表和有很多评论的项目。这些评论通过hasManyThrough items链接到列表。 名单如下:Laravel eloquent拥有许多模型访问权限,laravel,eloquent,Laravel,Eloquent,我有以下三种型号: -评论 -有许多评论的项目 -包含许多项的列表&hasManyThrough'comment'、'item' 这意味着我有很多项目的列表和有很多评论的项目。这些评论通过hasManyThrough items链接到列表。 名单如下: class List extends Model{ protected $fillable = ['title','description','user_id']; public function items() { return $thi
class List extends Model{
protected $fillable = ['title','description','user_id'];
public function items()
{
return $this->hasMany('App\Item');
}
public function comment()
{
return $this->hasManyThrough('App\Comment', 'App\Item');
}}
项目:
class Item extends Model
{
//
protected $guarded = [];
protected $fillable = ['title','description','user_id','list_id'];
public function comment(){
return $this->hasMany('App\Comment');
}
public function list(){
return $this->belongsTo('App\List');
}
}
和评论:
class Comment extends Model
{
//
protected $fillable = ['content','item_id','user_id'];
public function items(){
return $this->belongsTo('App\Item');
}
}
如何访问与每个列表相关的注释?
编辑:当我尝试访问id=15的列表的注释时,例如$list->comments,我得到以下错误:
SQLSTATE[42S22]:未找到列:1054“字段列表”中的未知列“items.list_id”SQL:选择注释。*,items.list_id作为laravel_,通过注释内部的键连接items.id=comments.item_id where items.list_id=15如果您尝试正常访问关系(例如$list->comment;)是否无效;?另一方面,我建议对返回集合的关系使用复数名称,即注释而不是注释。我认为这不起作用,因为我的注释表中没有列表id。您使用的是hasManyThrough,它基本上会获取属于列表项的所有注释。你有没有试过,但不起作用?https://laravel.com/docs/6.x/eloquent-relationshipshas-many-through 检查文档OK,items表上似乎没有列表id,这意味着您的某些其他关系也无法正常工作。请为这些表添加迁移。