Laravel 关系不';t在拉威尔工作(有很多)
我有一个带有键“slug”的类别模型和一个带有键“Category_slug”的广告模型,我需要得到所有相关的类别模型对象 这段代码有效,我得到了相关的模型Laravel 关系不';t在拉威尔工作(有很多),laravel,Laravel,我有一个带有键“slug”的类别模型和一个带有键“Category_slug”的广告模型,我需要得到所有相关的类别模型对象 这段代码有效,我得到了相关的模型 $cityAds = Ad::where('city_slug', $sCity)->first(); $city = $cityAds->categories; dd($city); 但是,如果我将first()更改为get(),则会得到错误属性[categories]在此集合实例上不存在 $cityAds = Ad::wh
$cityAds = Ad::where('city_slug', $sCity)->first();
$city = $cityAds->categories;
dd($city);
但是,如果我将first()更改为get(),则会得到错误属性[categories]在此集合实例上不存在代码>
$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
实例的集合,您的代码不知道如何处理[Ad,Ad,Ad]->类别。您需要使用->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()
还返回了一个集合
,因此$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
}
}
或者,最后,将您的关系调整为一个hasOne()
,如果您只需要一个Category
模型,那么请执行$cityAd->Category