2014-12-28 1 views
0

Airports Таблица:Laravel нетерпеливо не работает?

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); 
    } 

Часть г esponse:

[ 
{ 
"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" 
} 
] 

Я просто пытаюсь извлечь все данные полеты и нетерпеливый нагрузки все аэропорты с ним, но по какой-то причине реакция не имеет данных происхождения и назначения в нем. Я ошибаюсь в синтаксисе где-то или есть проблема с моей логикой?

ответ

3

Сначала вам нужно указать внешние ключи для своих отношений, так как вы не используете обычное именование.

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

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

Также вы столкнулись с проблемой, так как ваши отношения имеют то же имя, что и атрибуты моделей. Я предлагаю вам изменить столбцы дБ origin_id и destination_id (Вы можете также переименовать отношения, конечно)

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

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

Да, я понял, что в конце концов. Примите ваш ответ, как только он позволит мне. :) – Rohan

Смежные вопросы