简体   繁体   English

雄辩的关系命名约定

[英]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" article数据库名称是“ articles”

categoery db name is "article_categories" 类别数据库名称为“ 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? 现在我的问题是:我该如何命名将存储类别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. 因此您不必知道Eloquent使用的命名约定。

article_category_id should be the correct one. article_category_id应该是正确的。

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');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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