简体   繁体   English

如何使Laravel多对一(hasMany)关系有效

[英]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. 我关联了2个模型-类别和新闻,每个新模型可以为其分配1个类别。 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); 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. 该行将返回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. 因此,您应该使用foreach或仅获取集合的第一项。

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: 您可以按以下方式加载 news方法:

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

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

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