Laravel急切加载不工作?

时间:2014-12-28 16:07:40

标签: laravel laravel-4 eloquent eager-loading

机场表:

Schema::create('airports', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('city');
            $table->timestamps();
        });

航班表:

Schema::create('flights', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('number');
            $table->integer('origin')->unsigned();
            $table->foreign('origin')->references('id')->on('airports');
            $table->integer('destination')->unsigned();
            $table->foreign('destination')->references('id')->on('airports');
            $table->integer('price');
            $table->timestamps();
        });

飞行模型:

<?php

class Flight extends \Eloquent {
    protected $fillable = ['number', 'origin', 'destination'];

    public function origin(){
        return $this->belongsTo('Airport');
    }

    public function destination(){
        return $this->belongsTo('Airport');
    }
}

FlightController @指数:

public function index()
    {
        $flights = Flight::with('origin')->with('destination')->get();
        return Response::json($flights, 200);
    }

部分回复:

[
{
"id": "1",
"number": "112",
"origin": null,
"destination": null,
"price": "232",
"created_at": "2014-12-28 11:49:44",
"updated_at": "2014-12-28 11:49:44"
},
{
"id": "2",
"number": "812",
"origin": null,
"destination": null,
"price": "192",
"created_at": "2014-12-28 11:49:44",
"updated_at": "2014-12-28 11:49:44"
}
]

我只是试图获取所有航班数据并急切加载所有机场,但由于某种原因,响应中没有原始和目的地数据。我在某处的语法中犯了错误,或者我的逻辑有问题吗?

1 个答案:

答案 0 :(得分:4)

首先,您需要指定关系的外键,因为您没有使用传统的命名。

public function origin(){
    return $this->belongsTo('Airport', 'origin');
}

public function destination(){
    return $this->belongsTo('Airport', 'destination');
}

此外,您将遇到麻烦,因为您的关系与模型的属性具有相同的名称。我建议你将db列更改为origin_iddestination_id(当然也可以重命名关系)

public function origin(){
    return $this->belongsTo('Airport', 'origin_id');
}

public function destination(){
    return $this->belongsTo('Airport', 'destination_id');
}
相关问题