【发布时间】:2015-09-13 20:18:36
【问题描述】:
我正在尝试访问关系字段值,当我尝试执行此操作时,出现错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sub_areas.subarea_id' in 'where clause' (SQL: select * fromsub_areaswheresub_areas.subarea_idis null limit 1)
我不明白为什么要把它改成带下划线的小键;
感谢任何帮助。
访问模型:
$subArea = City::find(1)->subArea;
在模型中,主键是:
城市模型:
/**
* Overriding default Primary Key
* @var string
*/
protected $primaryKey = 'SubAreaID';
public function subArea()
{
return $this->belongsTo(SubArea::class);
}
子区域模型
public function city()
{
return $this->hasMany(City::class);
}
迁移:
Schema::create('cities', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('Id');
$table->integer('AreaID')->unsigned();
$table->integer('SubAreaID')->unsigned();
$table->integer('CityID')->unsigned()->index();
$table->string('Title', 50);
$table->string('Latitude', 100);
$table->string('Longitude', 100);
$table->tinyInteger('Active')->unsigned()->default(1);
});
添加外键:
Schema::table('cities', function(Blueprint $table) {
$table->foreign('AreaID')
->references('AreaID')->on('areas')
->onDelete('cascade')->onUpdate('restrict');
$table->foreign('SubAreaID')
->references('SubAreaID')->on('sub_areas')
->onDelete('cascade')->onUpdate('restrict');
});
如果我像这样在函数内部传递外键
城市模型
return $this->hasOne(SubArea::class, 'SubAreaID');
子区域模型
return $this->belongsToMany(\City::class, 'cities', 'SubAreaID');
我没有得到任何结果。 但这是另一个问题。
【问题讨论】:
-
您从哪个模型访问关系?你能展示你如何尝试访问关系的代码吗?
-
我已经编辑了我的问题
标签: php laravel laravel-4 laravel-5