简体   繁体   中英

Laravel 5.4 Relationship hasMany not working

i have 2 model Article and ArtCategories

I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake? .

Code model

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

This is DB structure Table up is pjt_article ,table down is pjt_categories_article 在此处输入图片说明

Result

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

在此处输入图片说明

Relation Not working

You should add foreign key in relation method of 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');
    }
}

Now fetch article with ArtCategories as:

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

As laravel convention Article() method should be articles() and ArtCategories() should be artCategory() .

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