douchi8503 2017-06-06 08:24
浏览 472
已采纳

SQLSTATE [42S22]:未找到列:1054未知列一对多(反)关系laravel

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 ?

  • 写回答

3条回答 默认 最新

  • doukanxi4246 2017-06-06 08:26
    关注

    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 the belongsTo 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧