繁体   English   中英

雄辩的关系命名约定

[英]Eloquent relationships naming conventions

我有有关类别的文章

许多文章,每个文章都属于一个类别。

每个类别都有很多文章

article数据库名称是“ articles”

类别数据库名称为“ 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');
    }
}

现在我的问题是:我该如何命名将存储类别ID的文章中的列?

我试图命名:

article_category_id
articleCategory_id
article_categories_id
articleCategories_id

他们都没有像我一样工作

$article->category 

雄辩地运行此查询:

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

谢谢

如果您在命名字段方面遇到麻烦,可以设置自己的密钥:

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

因此您不必知道Eloquent使用的命名约定。

article_category_id应该是正确的。

您可以尝试替换此代码吗

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

与下面的代码,如果这将工作类文章扩展模型

{
    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