【发布时间】:2018-06-08 16:26:52
【问题描述】:
我有两张桌子country 和state。
country 表包含country_id 和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();
【问题讨论】:
-
我编辑了您的问题并更改了一些类名的大小写。请确保您确实使用
PascalCase作为类名(即首字母大写和每个单词的首字母大写,即StateController)。您的代码中存在一些不一致,这将导致警告。
标签: laravel eloquent foreign-keys relational-database laravel-5.5