Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 关系不';t在拉威尔工作(有很多)_Laravel - Fatal编程技术网

Laravel 关系不';t在拉威尔工作(有很多)

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

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

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

$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