У меня есть таблицы: Тур и Страна. У таблицы Тур заранее предопределено, что только одна страна может соответствовать туру. Но, возможны ситуации, что несколько туров возможны в одной стране и появляется связь многие к одному.
Реализация вывода всех элементов:
@foreach($tours as $tour)
<form action="/">
<table class="tours">
<tr>
<td>Название: {{ $tour->name }}</td>
<td><input type="submit" value="Заказать" name="buy" class="button special"></td>
</tr>
<tr>
<td>Дата начала тура: {{ $tour->date_start }}</td>
<td>Дата завершения тура: {{ $tour->date_end }}</td>
</tr>
<tr>
<td>Количество человек: {{ $tour->people }}</td>
<td>Питание: <?php echo \App\Http\Controllers\MainController::getEat($tour->eat); ?></td>
</tr>
<tr>
<td>Страна: {{ $tour->country->name }}</td>
..
@endforeach
Мои миграции:
Schema::create('tours', function (Blueprint $table) {
$table->increments('id');
$table->string('name',40);
$table->date('date_start');
$table->date('date_end');
$table->integer('idCountry')->references('id')->on('countries');
...
}
//Внешний ключ
Schema::create('tours', function (Blueprint $table) {
$table->foreign('idCountry')->references('id')->on('countries');
}
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50);
$table->timestamps();
});
Метод country для получения из модели:
public function country(){
return $this->hasOne('App\Countries', 'id');
}
Ошибка заключается в том, что если создать одну страну и два тура, то при выводе всех элементов - падает ошибка на 2ом туре (у его тура id = 1 и он есть в БД, и его выводит) по причине того, что он пытается выбрать страну с id = 2 , хотя в БД id = 1.
Есть подозрения, что проблема в методе country().