I have two models Tour.php
and TourCategory.php
:
Tour.php
protected $table = `tours`;
public function category()
{
return $this->belongsTo('App\TourCategory');
}
TourCategory.php
protected $table = 'tcategories';
public function tours()
{
return $this->hasMany('App\Tour');
}
My db tables are as follows:
tours
table
id|title|category_id|content|
tcatgegories
table
id|name
And I have a view to show the all tours belonging to a category with the following code:
@foreach ($category->tours as $tour)
<tr>
<th>{{ $tour->id}}</th>
<td>{{ $tour->title}}</td>
<td>
<span class="label label-default">{{$category->name}}</span>
</td>
</tr>
@endforeach
With this above code I'm getting error of:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-masteresources\
views\admin\categories\show.blade.php
I have used same code for my previous projects also but didn't had any errors. Or am I missing something ?
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with
_id
. However, if the foreign key on the model is not*_id
, you may pass a custom key name as the second argument to thebelongsTo
method
So, you need to specify a foreign key:
public function category()
{
return $this->belongsTo('App\TourCategory', 'category_id');
}
You may also override the foreign and local keys by passing additional arguments to the
hasMany
method.
public function tours()
{
return $this->hasMany('App\Tour', 'category_id');
}
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
Or use tour_category_id
instead of category_id
in the tours table.
this column tour_category_id
lis not found in your tours
table, change your sql query to
select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null
in Tour.php
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function tours()
{
return $this->hasMany(Tour::class, 'category_id');
}
in TourCategory.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(TourCategory::class, 'category_id');
}