首页 > 解决方案 > 如何在 Laravel Eloquent 中使用一对多关系连接?

问题描述

我有两张桌子countrystate. country_idcountry 表具有和列country_name。状态表具有state_idstate_namecountry_id

我想在输出中显示state_id和。state_namecountry_name

Country模型:

class Country extends Model
{
    protected $table = 'country';
    protected $fillable = ['country_name'];
    public $timestamps = false;
    protected $primaryKey = 'country_id';

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

State模型:

class State extends Model
{
    protected $table = 'state';
    protected $fillable = ['state_name','country_id'];
    public $timestamps = false;
    protected $primaryKey = 'state_id';

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

StateController的是:

$country_state_data = State::with('country_name')->get();

标签: laraveleloquentforeign-keysrelational-databaselaravel-5.5

解决方案


利用

$country_state_data = state::with('country')->get();

在你看来

@foreach($country_state_data as $state)
    {{ $state->country->country_name }}
@endforeach

推荐阅读