Reputation: 13811
Airports Table:
Schema::create('airports', function(Blueprint $table)
{
$table->increments('id');
$table->string('code');
$table->string('name');
$table->string('city');
$table->timestamps();
});
Flights Table:
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();
});
Flight Model:
<?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@index:
public function index()
{
$flights = Flight::with('origin')->with('destination')->get();
return Response::json($flights, 200);
}
Part of the response:
[
{
"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"
}
]
I am simply trying to fetch all the flights data and eager load all the airports with it but for some reason the response does not have the origin and destination data in it. Am I making a mistake in the syntax somewhere or is there a problem with my logic?
Upvotes: 0
Views: 7322
Reputation: 153140
First you need to specify the foreign keys for your relation since you are not using the conventional naming.
public function origin(){
return $this->belongsTo('Airport', 'origin');
}
public function destination(){
return $this->belongsTo('Airport', 'destination');
}
Also you will run into trouble since your relations have the same name as attributes of the models. I suggest you change the db columns to origin_id
and destination_id
(You could also rename the relationships of course)
public function origin(){
return $this->belongsTo('Airport', 'origin_id');
}
public function destination(){
return $this->belongsTo('Airport', 'destination_id');
}
Upvotes: 6