我正在尝试将“简单”关系添加到我的路线模型中,但我一定是忽略了一些东西,因为它不起作用。
我希望我的路线有很多步骤,而这些步骤应该只有一个路线,但我的代码没有找到任何步骤。我错过了什么?
路由表:
Schema::create('routes', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid')->unique();
$table->decimal('start_lat', 11, 8);
$table->decimal('start_lng', 11, 8);
$table->decimal('end_lat', 11, 8);
$table->decimal('end_lng', 11, 8);
$table->string('start_address');
$table->string('end_address');
$table->integer('distance');
$table->integer('duration');
$table->timestamps();
});
步骤表:
Schema::create('steps', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid')->unique();
$table->integer('route_id')->unsigned();
$table->foreign('route_id')->references('id')->on('routes');
$table->integer('distance');
$table->integer('duration');
$table->decimal('start_lat', 11, 8);
$table->decimal('start_lng', 11, 8);
$table->decimal('end_lat', 11, 8);
$table->decimal('end_lng', 11, 8);
$table->string('instructions');
$table->text('polyline');
});
路由模型:
public function steps() {
return $this->hasMany(Step::class, 'route_id', 'id');
}
步骤模型:
public function route() {
return $this->belongsTo(Route::class);
}
我在 Controller 中的调用方式:
$route = Route::all()->where('id', 1)->first();
$steps[] = $route->steps();
最佳答案
您可能想要一个带台阶的系列?
但是你反而得到了 Eloquent steps()
尝试将其更改为:
$steps[] = $route->steps;
关于php - Eloquent 模型中的 Laravel 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52527101/