I've a one-to-many relationship with models
class Article extends Eloquent {
protected $table = 'articles';
public function categories()
{
return $this->belongsTo('ArticleCategory');
}
}
class ArticleCategory extends Eloquent {
protected $table = 'articles_categories';
public function articles()
{
return $this->hasMany('Article');
}
}
In my controller I'm trying to grab all articles from a category
$categories = ArticleCategory::find(1);
$article = $categories->articles;
return $article;
and that works perfectly.
But when I'm trying to make an inverse
$article = Article::find(1);
$category = $article->categories;
return $category;
I'm getting null
. I should get a category return for an article id in find().
Database tabels:
- articles: Id | title | description | category_id
- articles_categories: Id | title
Since it's one to many relationship you can easily do this
$category = ArticleCategory::find($article->category_id);
I think the error is in the naming in your database fields. The field in your articles
table which is pointing to the articles_categories
should be name articles_categories_id
.
Try this
public function categories()
{
return $this->belongsTo('ArticleCategory','category_id');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.