简体   繁体   中英

Eloquent relationships naming conventions

I have articles with categories

many articles each article belong to one category.

each category has many articles

article db name is "articles"

categoery db name is "article_categories"

class Article extends Model
{
    public function category()
    {
        return $this->belongsTo('App\ArticleCategory');
    }
}
class ArticleCategory extends Model
{
    public function articles()
    {
        return $this->hasMany('App\Article');
    }
}

now my question is: how should I name the column in articles which will store the category id?

I tried naming it:

article_category_id
articleCategory_id
article_categories_id
articleCategories_id

all of them not working as if I do

$article->category 

eloquent running this query:

select * from `article_categories` where `article_categories`.`id` is null limit 1

thanks

If you have troubles with naming fields you can set your own keys:

public function category()
{
    $this->belongsTo('App\ArticleCategory', 'local_key', 'parent_key');
}

so you don't have to be aware of naming convenctions used by Eloquent.

article_category_id should be the correct one.

can you try replacing this code

class Article extends Model
{
    public function category()
    {
        return $this->belongsTo('App\ArticleCategory');
    }
}

with the code below if this would work class Article extends Model

{
    public function category()
    {
        return $this->belongsTo('App\ArticleCategory', 'article_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM