【问题标题】:Eloquent ORM One to many query is not working雄辩的 ORM 一对多查询不起作用
【发布时间】:2026-02-14 00:45:01
【问题描述】:

我正在使用 laravel 5.4。我创建了国家和州表。

国家/地区表如下所示

我的状态表是:

在这里,我编写了如下所示的连接查询。效果很好。

$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 而不是编写此查询,那么我应该编写什么查询?

在 Country 模型中,我创建了如下所示的函数:

public function states()
{
    return $this->hasMany('state');
}

在状态模型中,我编写了如下所示的函数:

public function country()
{
    return $this->hasOne('country');
}

【问题讨论】:

    标签: eloquent laravel-5.4


    【解决方案1】:

    Country 模型中试试这个:

    public function states()
    {
        return $this->hasMany(App\State::class);
    }
    

    State 模型中:

    public function country()
    {
        return $this->belongsTo(App\Country::class);
    }
    

    然后$country->states 会给你这个国家的所有州。以及$state->country 将返回国家/地区。

    官方文档:Eloquent: Relationships

    【讨论】: