首页 > 解决方案 > 关系在 Laravel 中不起作用(hasMany)

问题描述

我有一个带有键“slug”的类别模型和一个带有键“category_slug”的广告模型,我需要获取所有相关的类别模型对象

这段代码有效,我得到了相关的模型

$cityAds = Ad::where('city_slug', $sCity)->first();
$city = $cityAds->categories;
dd($city);

但是,如果我将 first () 更改为 get () 我会收到错误Property [categories] does not exist on this collection instance.

$cityAds = Ad::where('city_slug', $sCity)->get();
$city = $cityAds->categories;
dd($city);

我的广告模型有关系

public function categories() {
    return $this->hasMany(Category::class, 'slug', 'category_slug');
}

标签: laravel

解决方案


$cityAds,当您使用->get()的是多个Ad实例的 Collection 时,您的代码不知道如何处理[Ad, Ad, Ad]->categories. 您需要使用->first()(如在您的工作示例中)或循环$ads

$cityAds = Ad::where('city_slug', $sCity)->first();
$city = $cityAds->categories;
dd($city);

// OR

$cityAds = Ad::where('city_slug', $sCity)->get();
foreach($cityAds as $cityAd) {
  $city = $cityAd->categories; // Do something with `$city` in this loop
}

作为旁注,categories()也返回 a Collection,因此$city变量名没有多大意义。考虑以下:

$cityAds = Ad::with('categories')->where('city_slug', $sCity)->get();
foreach($cityAds as $cityAd) {
  foreach ($cityAd->categories as $category) {
    // Do something with `$category` in this nested loop
  }
}

或者,最后,将您的关系调整为 a hasOne(),如果您只期望一个Category模型,那么执行$cityAd->category


推荐阅读