Laravel 模型关系。哪一个?
Laravel Model Relationship. which one?
嘿,所以我应该首先说我得到了这个数据库来使用。所以不确定他们使用的是什么关系。我最终需要做的是获取分配给文章的类别的名称。
基本上是这样的articles <> article_categories <> categories
article_categories 是连接器
条
|ID|header|body|ect...|
类别
|ID|parent_group|name|
article_categories
|article_id|category_id|
所以我认为这可能是一个 hasManyThrough
但只有错误。这也可能是我的论据做错了。
我首先尝试的是在 articles 模型中(由此出错)
public function category(){
return $this->hasManyThrough('App\categories' , 'App\article_categories' ,'article_id' , 'category_id');
}
希望我解释一下我的情况。我需要使用 has many through
还是我把它复杂化了?
-谢谢
不需要hasManyThrough
belongsToMany
就是你所需要的。
public function category(){
return $this->belongsToMany('App\categories' , 'article_categories' ,'article_id' , 'category_id');
}
在您的 article_categories 模型中试试这个
为类别创建函数
public function categories(){
return $this->belongsTo('App\Categories' , 'category_id');
}
文章也一样
public function articles(){
return $this->belongsTo('App\Articles' , 'article_id');
}
只是建议对模型使用单数形式,我不知道是否可以对迁移说 "plural":
迁移:文章,模型:文章
也一样
迁移:类别,型号:类别
希望对您有所帮助!祝你好运
嘿,所以我应该首先说我得到了这个数据库来使用。所以不确定他们使用的是什么关系。我最终需要做的是获取分配给文章的类别的名称。
基本上是这样的articles <> article_categories <> categories
article_categories 是连接器
条
|ID|header|body|ect...|
类别
|ID|parent_group|name|
article_categories
|article_id|category_id|
所以我认为这可能是一个 hasManyThrough
但只有错误。这也可能是我的论据做错了。
我首先尝试的是在 articles 模型中(由此出错)
public function category(){
return $this->hasManyThrough('App\categories' , 'App\article_categories' ,'article_id' , 'category_id');
}
希望我解释一下我的情况。我需要使用 has many through
还是我把它复杂化了?
-谢谢
不需要hasManyThrough
belongsToMany
就是你所需要的。
public function category(){
return $this->belongsToMany('App\categories' , 'article_categories' ,'article_id' , 'category_id');
}
在您的 article_categories 模型中试试这个
为类别创建函数
public function categories(){
return $this->belongsTo('App\Categories' , 'category_id');
}
文章也一样
public function articles(){
return $this->belongsTo('App\Articles' , 'article_id');
}
只是建议对模型使用单数形式,我不知道是否可以对迁移说 "plural":
迁移:文章,模型:文章
也一样迁移:类别,型号:类别
希望对您有所帮助!祝你好运