调用未定义的方法Illuminate \ Database \ Query \ Builder :: contains()

时间:2014-07-11 09:19:47

标签: php laravel-4 eloquent

调用未定义的方法Illuminate \ Database \ Query \ Builder :: contains()

以下是我的模特:

DepartCity.php

class DepartCity extends Eloquent {
protected $guarded = array();

public static $rules = array();

public function countries() {
    return $this->belongsToMany('Country', 'depart_cities_countries', 'depcity_id',     'country_id');
}

public $timestamps = false;

}

Country.php

class Country extends Eloquent {
protected $guarded = array();

public static $rules = array();

public function depart_cities() {
    return $this->belongsToMany('DepartCity', 'depart_cities_countries', 'country_id', 'depcity_id');
}

public function resorts() {
    return $this->hasMany('Resort');
}

public $timestamps = false;
}

以下是我的代码的一部分:

        $dep_cities = DepartCity::all(); 
    foreach ($dep_cities as $sletat_city) {
        $countries = $swc->getCountries($sletat_city->sletat_id)->GetCountriesResult->Country;
        foreach ($countries as $sletat_country) {
            $sletat_country_id = $sletat_country->Id;
            $country = (Country::where(array ('sletat_id' => $sletat_country_id))->first());
            if (!$country) {
                $country = new Country;
                $country->sletat_id = $sletat_country_id;
            }
            $country->name = $sletat_country->Name;
            $country->save();

            if (!($country->depart_cities()->contains($sletat_city->Id))) {
                $country->depart_cities()->save($sletat_city);
            } 
        }
    }

在此处收到错误:

(!($country->depart_cities()->contains($sletat_city->Id)))

类$ country-> depart_cities()的类型是Illuminate \ Database \ Eloquent \ Relations \ BelongsToMany并且没有方法“包含”但我无法理解如何运作

请帮助我:)

1 个答案:

答案 0 :(得分:3)

更改以下内容;

 $country = (Country::with('depart_cities')->where(array ('sletat_id' => $sletat_country_id))->first());

 if (!($country->depart_cities->contains($sletat_city->Id))) {
       $country->depart_cities()->save($sletat_city);
 }