laravel - 关系在 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');
}
解决方案
$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
推荐阅读
- list - 不同列表的两个元素之间的差异。表现;
- python - 我无法理解函数定义(带有 '=' 的参数)
- sql - PostgresQL - 为 SELECT 查询定义 SEQUENCE
- excel - 在同一个 Excel 图表中显示多个时间序列
- mysql - Ruby on rails 将行转换为列
- reactjs - 在 react.js 中将大小调整为移动设备时,如何更改为新页面?
- azure - 尝试从 docker 容器对 Azure AAD 进行身份验证
- javascript - NodeJS:从循环中的多个TSV文件异步返回数据
- html - 如何将文本移动到页面的顶部和中心?
- python - 在精确文本匹配时重新索引数据框