laravel - 如何在 Laravel Eloquent 中使用一对多关系连接?
问题描述
我有两张桌子country
和state
. country_id
country 表具有和列country_name
。状态表具有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
推荐阅读
- javascript - 使用 puppeteer 在站点完全加载之前尝试获取屏幕截图和数据
- adaptive-cards - 自适应卡片从 if 条件更改文本颜色
- python - Django / Python:TypeError at /'NoneType'对象不可下标
- xamarin - NSData Sha512 哈希与 Xamarin
- django - Django all auth facebook login with Use Strict Mode for Redirect URIs
- python - Python Flask:后台发生了什么以及如何只调用一次函数?
- r - R:“参数长度为 0”(空图)
- html - HTML 表单 POST 方法将“+”作为 %2B,将“=”作为 %3D。如何获得原始的“+”和“=”符号?
- machine-learning - 写出Tif时将RasterFrameLayer转换为Raster时如何修复NPE?
- netsuite - NetSuite:为什么?库存分类帐不等于资产负债表和/或总帐的库存帐户余额