【问题标题】:SQLSTATE[42S22]: Column not found: 1054 Unknown column one to many(inverse) relation laravelSQLSTATE [42S22]:未找到列:1054 未知列一对多(反向)关系 laravel
【发布时间】:2017-11-07 04:05:00
【问题描述】:

我有两个型号Tour.phpTourCategory.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');
}

我的数据库表如下:

tours

id|title|category_id|content|

tcatgegories

id|name

我希望使用以下代码显示属于某个类别的所有游览:

    @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

使用上面的代码,我收到以下错误:

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-master\resources\
views\admin\categories\show.blade.php

我之前的项目也使用了相同的代码,但没有任何错误。还是我错过了什么?

【问题讨论】:

    标签: php mysql laravel blade laravel-5.4


    【解决方案1】:

    Eloquent 通过检查关系方法的名称并在方法名称后面加上_id 来确定默认的外键名称。但是,如果模型上的外键不是*_id,您可以将自定义键名称作为第二个参数传递给belongsTo 方法

    所以,你需要specify a foreign key:

    public function category() 
    {
        return $this->belongsTo('App\TourCategory', 'category_id');
    }
    

    您还可以通过将其他参数传递给hasMany 方法来覆盖外键和本地键。

    public function tours()
    {
        return $this->hasMany('App\Tour', 'category_id');
    }
    

    https://laravel.com/docs/5.4/eloquent-relationships#one-to-many

    或者在游览表中使用tour_category_id 而不是category_id

    【讨论】:

    • 添加了category_id 作为外键,错误依旧。
    • @TanjaForsberg 您最初的问题是关于反向一对多关系(即belongsTo())。如果您使用tours() 关系,您还需要将自定义外键名称添加到hasMany() 关系。您可以在更新的答案中看到一个示例。
    • 感谢您的宝贵指导。我会永远记住您的建议。
    【解决方案2】:

    在 Tour.php 中

     /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function tours()
    {
        return $this->hasMany(Tour::class, 'category_id');
    } 
    

    在 TourCategory.php 中

    /**
         * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
         */
        public function category()
        {
            return $this->belongsTo(TourCategory::class, 'category_id');
        }
    

    【讨论】:

      【解决方案3】:

      在您的tours 表中找不到此列tour_category_id,请将您的sql 查询更改为

      select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null
      

      【讨论】:

      • 我知道,但我过去在 tours 中拥有并且过去拥有 category_id 字段。应用正在寻找不存在的列。
      猜你喜欢
      • 2018-02-21
      • 2015-12-08
      • 2018-11-02
      • 2019-10-02
      • 1970-01-01
      • 2016-04-09
      • 2017-04-03
      相关资源
      最近更新 更多