我在调用我的航班计划表中的出发ICAO和到达ICAO时遇到了问题。Laravel一直报错,说我的关系有问题。以下是代码。
Schema::create('airports', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('city');
$table->string('country');
$table->string('iata');
$table->string('icao');
$table->double('lat');
$table->double('lon');
$table->longText('data')->nullable(); //JSON Data for All gate information for the system.
$table->softDeletes();
});
Schema::create('schedule_templates', function (Blueprint $table) {
$table->increments('id');
$table->string('code');
$table->string('flightnum');
$table->integer('depicao')->unsigned();
$table->foreign('depicao')->references('id')->on('airports')->onDelete('cascade');
$table->integer('arricao')->unsigned();
$table->foreign('arricao')->references('id')->on('airports')->onDelete('cascade');
$table->string('aircraft')->nullable();
$table->boolean('seasonal');
$table->date('startdate');
$table->date('enddate');
$table->time('deptime');
$table->time('arrtime');
$table->integer('type');
$table->boolean('enabled');
$table->text('defaults');
$table->timestamps();
$table->softDeletes();
});
以下是模型列表
class ScheduleTemplate extends Model
{
public $table = "schedule_templates";
public function depicao()
{
return $this->hasOne('App\Models\Airport', 'depicao');
}
public function arricao()
{
return $this->hasOne('App\Models\Airport', 'arricao');
}
}
class Airport extends Model
{
//
public $timestamps = false;
public function schedules()
{
return $this->belongsToMany('App\ScheduleTemplate');
}
}
当我尝试使用以下代码进行查询时,出现以下错误
SQLSTATE[42S22]: 列不存在: 1054 Unknown column 'vaos_airports.depicao' in 'where clause' (SQL: select * from
vaos_airports
wherevaos_airports
.depicao
in (1))
$schedules = ScheduleTemplate::with('depicao')->with('arricao')->get();
最终目标是将结果放入表格中。如果您感兴趣,这是相关代码。
@foreach($schedules as $s)
<tr>
<td>{{$s->code}}</td>
<td>{{$s->flightnum}}</td>
<td>{{$s->depicao()->name}}</td>
<td>{{$s->arricao()->name}}</td>
<td>{{$s->aircraft}}</td>
<td>{{$s->seasonal}}</td>
<td>{{$s->type}}</td>
</tr>
@endforeach
编辑:
我已经解决了关系问题,显然我把它们弄反了。这是更新后的模型类。
class ScheduleTemplate extends Model
{
public $table = "schedule_templates";
public function depicao()
{
return $this->belongsTo('App\Models\Airport', 'depicao');
}
public function arricao()
{
return $this->belongsTo('App\Models\Airport', 'arricao');
}
}
class Airport extends Model
{
//
public $timestamps = false;
public function schedules()
{
return $this->hasMany('App\ScheduleTemplate');
}
}
现在出错的地方在于视图文件。我会遇到BelongsTo错误:
未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name
或者如果我没有使用“()”就有arricao或depicao:
试图获取非对象属性