Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

Relationships don't work in Laravel(hasMany)

I have a Category model with key 'slug' and an Ad model with key 'category_slug' and I need to get all related Category model objects

This code works and I get the associated model

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

But, if I change first () to get () I get the error Property [categories] does not exist on this collection instance.

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

My Ad model has a relation

public function categories() {
    return $this->hasMany(Category::class, 'slug', 'category_slug');
}
question from:https://stackoverflow.com/questions/65945032/relationships-dont-work-in-laravelhasmany

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$cityAds, when you use ->get() is a Collection of multiple Ad instances, and your code doesn't know how to handle [Ad, Ad, Ad]->categories. You need to use ->first() (like in your working example), or loop over $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
}

As a side note, categories() is also returning a Collection, so $city as the variable name doesn't make a lot of sense. Consider the following:

$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
  }
}

Or, lastly, adjust your relationship to a hasOne(), if you're only expecting a single Category model, then do $cityAd->category


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...