简体   繁体   中英

How to make laravel Many-To-One (hasMany) relationship works

I related 2 models - Category and News, each new can have 1 category assign to itself. The problem is that I can't access the category that I assigned to the new, my question is how to make it work ? And why my way doesn't work.

Categroy model-

public function news(){
    return $this->hasMany('App\News');
}

News model -

public function category(){
    return $this->belongsTo('App\Categroy');
}

CategoryController - $categories = DB::table('categroys')->get(); dd($categories->news); $categories = DB::table('categroys')->get(); dd($categories->news);

message -

"Property [news] does not exist on this collection instance."
  1. This line will return instance of Collection. It is not a model itself. It is all items in categories table. $categories = DB::table('categroys')->get();

     foreach($categories as $category) { $news = $category->news(); } 
  2. But in this case you will get a first item and it is a model

      $categories = DB::table('categroys')->first(); 

So you should use either foreach or take only the first item of collection.

This is Eloquent Relationships . This relationship only works with Model.

$categories = Categroy::all();

foreach($categories as $category) {
    // $category->news
}

You can eager loading your news method as follow:

$categories = Category::with(['news'])->get();
dd($caregories);

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