Eloquent ORM 一对多查询不起作用
Eloquent ORM One to many query is not working
我正在与 laravel 5.4 合作。我创建了国家和州 table.
国家table如下所示
我的状态 table 是:
在这里,我编写了如下所示的连接查询。效果很好。
$state = DB::table($this->tbl_states)
->join($this->tbl_countries, $this->tbl_countries.'.id', '=', $this->tbl_states.'.country_id')
->select($this->tbl_states.'.*', $this->tbl_countries.'.name as country_name')
->whereNull($this->tbl_states.'.deleted_at')
->paginate(10)
但是,我不想写这个查询,而是想使用 Eloquent ORM 那么我应该写什么查询?
在国家/地区模型中,我创建了如下所示的函数:
public function states()
{
return $this->hasMany('state');
}
在状态模型中,我有如下所示的写入函数:
public function country()
{
return $this->hasOne('country');
}
在 Country
模型中试试这个:
public function states()
{
return $this->hasMany(App\State::class);
}
并且在 State
模型中:
public function country()
{
return $this->belongsTo(App\Country::class);
}
然后 $country->states
会给你这个国家的所有州。 $state->country
以及 return 州的国家。
我正在与 laravel 5.4 合作。我创建了国家和州 table.
国家table如下所示
我的状态 table 是:
在这里,我编写了如下所示的连接查询。效果很好。
$state = DB::table($this->tbl_states)
->join($this->tbl_countries, $this->tbl_countries.'.id', '=', $this->tbl_states.'.country_id')
->select($this->tbl_states.'.*', $this->tbl_countries.'.name as country_name')
->whereNull($this->tbl_states.'.deleted_at')
->paginate(10)
但是,我不想写这个查询,而是想使用 Eloquent ORM 那么我应该写什么查询?
在国家/地区模型中,我创建了如下所示的函数:
public function states()
{
return $this->hasMany('state');
}
在状态模型中,我有如下所示的写入函数:
public function country()
{
return $this->hasOne('country');
}
在 Country
模型中试试这个:
public function states()
{
return $this->hasMany(App\State::class);
}
并且在 State
模型中:
public function country()
{
return $this->belongsTo(App\Country::class);
}
然后 $country->states
会给你这个国家的所有州。 $state->country
以及 return 州的国家。