如何在Laravel Eloquent中使用一对多关系加入?
How to use join using One-to-Many relationship in Laravel Eloquent?
我有两个 tables country
和 state
。
国家 table 有 country_id
和 country_name
列。
状态 table 具有列 state_id
、state_name
和 country_id
。
我想在输出中显示state_id
、state_name
和country_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();
使用
$country_state_data = state::with('country')->get();
在你看来
@foreach($country_state_data as $state)
{{ $state->country->country_name }}
@endforeach
你快到了。您要做的是使用 State::get()
获取所有状态的列表。然后在 get()
之前添加 with('country')
,以便将其添加到查询构建器中。如您所见,country
是您想要预先加载的关系的名称。之后,您可以访问 country
的所有属性,就像您可以访问 state
:
的属性一样
$states = State::with('country')->get();
foreach ($states as $state) {
echo "ID: {$state->id}, State: {$state->name}, Country: {$state->country->name}";
}
会输出类似
的内容
ID: 1, State: Vorarlberg, Country: Austria
ID: 2, State: Bavaria, Country: Germany
经过一些调查,似乎在更改主键时,将键添加到关系定义中是有意义的:
public function country()
{
return $this->belongsTo(Country::class, 'country_id', 'country_id');
}
否则,关系无法正确加载。
我有两个 tables country
和 state
。
国家 table 有 country_id
和 country_name
列。
状态 table 具有列 state_id
、state_name
和 country_id
。
我想在输出中显示state_id
、state_name
和country_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();
使用
$country_state_data = state::with('country')->get();
在你看来
@foreach($country_state_data as $state)
{{ $state->country->country_name }}
@endforeach
你快到了。您要做的是使用 State::get()
获取所有状态的列表。然后在 get()
之前添加 with('country')
,以便将其添加到查询构建器中。如您所见,country
是您想要预先加载的关系的名称。之后,您可以访问 country
的所有属性,就像您可以访问 state
:
$states = State::with('country')->get();
foreach ($states as $state) {
echo "ID: {$state->id}, State: {$state->name}, Country: {$state->country->name}";
}
会输出类似
的内容ID: 1, State: Vorarlberg, Country: Austria
ID: 2, State: Bavaria, Country: Germany
经过一些调查,似乎在更改主键时,将键添加到关系定义中是有意义的:
public function country()
{
return $this->belongsTo(Country::class, 'country_id', 'country_id');
}
否则,关系无法正确加载。