Laravel 5.4关系hasMany无效

时间:2018-06-30 03:34:20

标签: php database laravel relationship

我有2个模型文章和艺术类别

我使用belongsTo()和hasMany()在两个模型之间建立了一对多关系。 hasMany()关系可以正常工作,但是belongTo()不起作用。有人知道我在哪里弄错了吗?

代码模型

class ArtCategories extends Model
{
    protected $table = 'pjt_categories_article';
    protected $primaryKey = 'cate_id';
    protected $fillable = ['cate_id','categories'];

    public function Article(){
        return $this->hasMany(Article::class);
    }
}
class Article extends Model
{
    protected $table = 'pjt_article';
    protected $primaryKey = 'article_id';
    protected $fillable = ['article_id','title','descriptions','username','cate_id','status','visit','reference'];

    public function ArtCategories(){
        return $this->belongsTo(ArtCategories::class,'cate_id');
    }

    public function admin(){
        return $this->belongsTo(Admin::class);
    }
}

这是数据库结构上表是pjt_article,下表是pjt_categories_article enter image description here

结果

$art = Article::findOrFail($article_id); $cate = ArtCategories::pluck('categories', 'cate_id'); dd($art);

enter image description here

关系不正常

1 个答案:

答案 0 :(得分:1)

您应在ArtCategories的关联方法中添加外键

class ArtCategories extends Model
{
    protected $table = 'pjt_categories_article';
    protected $primaryKey = 'cate_id';
    protected $fillable = ['cate_id','categories'];

    public function article(){
         return $this->hasMany(Article::class, 'cate_id');
    }
}

现在以ArtCategories的形式获取文章:

$art = Article::with('ArtCategories')->findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
  

根据laravel约定,Article()方法应为articles()ArtCategories()应为artCategory()