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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作