php - Eloquent 模型中的 Laravel 关系

标签 php database laravel

我正在尝试将“简单”关系添加到我的路线模型中,但我一定是忽略了一些东西,因为它不起作用。

我希望我的路线有很多步骤,而这些步骤应该只有一个路线,但我的代码没有找到任何步骤。我错过了什么?

路由表:

     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/

相关文章:

java - 是否可以创建加密的 Sqlite 数据库?

javascript - 使用 Ajax 和 Bootstrap Modal 进行 Laravel 表单验证问题

javascript - FullCalendar v4 动态设置日历的高度

php - Laravel Logging - 自定义 channel 不写

php - 如何使用 html 下拉列表将数据添加到 codeigniter 中的数据库表?

php - 如何使用 PHP curl 命令行发送 header ?

php - 在数据库搜索中找不到数据的正确的其他条件是什么

php - PHP 中的并行处理 - 你是怎么做到的?

php - 无法让委托(delegate)方法发挥作用

c# - 如何在 C# 中使用动态名称在 Microsoft Access 中创建表?