我是拉威尔的新手,我正在从事一个项目,我想检索地址表的全部细节,包括城市名称、州名称和国家名称。
下面是代码。
$addresses = App\Address::with('countries', 'states','cities')->get();
return $addresses;
当我运行代码我得到一个错误
BadMethodCallException in Builder.php line 2161:
Call to undefined method Illuminate\Database\Query\Builder::countries()
请帮帮我。
城市表
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('states');
$table->string('cityName', 50);
$table->timestamps();
});
状态表
Schema::create('states', function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
$table->string('stateName', 50);
$table->timestamps();
});
国家表
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('countryName', 50);
$table->timestamps();
});
地址表
Schema::create('addresses', function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('states');
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities');
$table->string('firstLine', 50);
$table->string('secondLine', 50);
$table->string('thirdLine', 50);
$table->string('zipCode', 50);
$table->timestamps();
});
在模特城
class City extends Model
{
// City belongs to a State
public function city(){
return $this->hasOne('App\State');
}
public function address(){
return $this->belongsTo('Address');
}
}
状态
class State extends Model
{
// State has many Cities
public function cities(){
return $this->hasMany('App\City');
}
// State belongs to a Country
public function country(){
return $this->hasOne('App\Country');
}
public function address(){
return $this->belongsTo('Address');
}
}
国
class Country extends Model
{
// Country has many States
public function states(){
return $this->hasMany('App\State');
}
public function address(){
return $this->belongsTo('Address');
}
}
住址
class Address extends Model
{
// Address has one City
public function cities(){
return $this->hasOne('App\City','city_id');
}
// Address has one State
public function states(){
return $this->hasOne('App\State','state_id');
}
// Address has one Country
public function countries(){
return $this->hasOne('App\Country','country_id');
}
}
既然我们可以访问帖子的所有评论,那么让我们定义一个关系,允许评论访问其父帖子。要定义hasMany关系的倒数,请在子模型上定义一个关系函数,该函数调用belongsTo方法:
一对多看
你有一个国家有许多国家,逆关系是国家有一个国家。因此,您应该在模型State更改方法国家()中这样
public function country(){
return $this->belongsTo('App\Country');
}
并使用State::with('country')
附笔。
并检查其他型号。