代码之家  ›  专栏  ›  技术社区  ›  Christian Gallarmin

Laravel版本升级会影响您的控制器吗?

  •  1
  • Christian Gallarmin  · 技术社区  · 7 年前

    我的报表控制器

    use App\Site;
    use App\Report;
    
    
    public function showSpecificSite($site_id){
    
    $reports = Report::whereHas('site', function($query) use($site_id) {
        $query->where('site_id', $site_id);
    })->get(['email_date', 'url', 'recipient', 'report_id', 'site_id']);
    
    $siteName = Site::find($site_id)->site_name;
    
    return view('newsite', compact('site_id', 'siteName', 'reports'));
    }
    
    Route::get('sites/{site_id}',['as'=>'SpecificSite','uses'=>'ReportController@showSpecificSite']);
    

    场地模型

    public function report()
    {
        return $this->hasMany('App\Report');
    }
    

    public function site()
    {
        return $this->belongsTo('App\Site');
    }
    

    我的刀刃视图

    <a href="{{route('SpecificSite',['site_id'=>$record->site_id])}}">view</a>
    

    这是我升级我的拉威尔版本5.2.36到5.4.36的问题 Laravel Function that hold two parameters

    SQLSTATE[42S22]:未找到列:1054未知列'reports.site_站点id'in'where子句'(SQL:select email_date , url recipient , report_id , site_id reports 存在的位置(从中选择* sites site_site_id = 地点 . 站点id 站点id =1)

    我的路线:单子和以前一样。我还有我的routes/web.app文件夹。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Tobias K.    7 年前

    由于错误涉及一个在关系中使用的列,因此更可能是由于Laravel如何在关系(模型类)中“猜测”FK列名而发生了更改,而不是控制器中的更改。

    您可以在可选参数中明确指定FK名称 belongsTo ,那么它就不会猜到了。检查签名:

    public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    

    假设报表表中的FK名为 site_id

    public function site()
    {
        return $this->belongsTo('App\Site', 'site_id');
    }
    

    我稍微研究了一下,发现了突破性的变化(在5.4中介绍): https://github.com/laravel/framework/pull/16847 .

    the 5.4 Upgrade Guide :

    如果在定义关系时未显式指定外键,则Eloquent现在将使用相关模型的表名和主键名来生成外键。(…)[T]如果重写 $primaryKey getKeyName [相关]模型的方法。

    推荐文章