【问题标题】:laravel Eloquent ORM custom field namelaravel Eloquent ORM 自定义字段名
【发布时间】:2016-06-26 14:41:56
【问题描述】:

我正在尝试使用 Eloquent 并使用以下代码从包含字段 productsid 的产品表中获取记录。我的型号名称是 Products_description。

在我的路线文件中。

Route::get('product/{productsid}','productscontroller@show');

在我的控制器文件中

public function show($productid)
{
$Products = Products_description::find($productid);
return $Products;   
}

但它向我显示了Unknown column 'products_description.id' 的错误。看起来 Eloquent 默认尝试通过字段名称 id 获取记录,就像使用表名称一样。但是如何通过id以外的表字段获取记录。例如如果是productid,我们会做什么/使用什么?

【问题讨论】:

  • 你能告诉我表结构和Products_description模型类吗?
  • 表名是 'products_description' 字段是 'productsid' int(11), 'product_name' varchar(64)。类 Products_description 扩展模型 { protected $table = 'products_description'; }

标签: laravel eloquent


【解决方案1】:

在你的模型中,声明你的$primaryKey

class Products_description {
    protected $primaryKey = "productid";

    //
}

这样您可以使用::findfirstOrFail 而不是where

【讨论】:

    【解决方案2】:

    喜欢这个

     $Products = Products_description::where('pruductid',$productid)->first();
    

    或者你可以试试这个

    产品描述模型

      class Products_description extends Eloquent {
    
    protected $primaryKey = 'productid';
      }
    

    【讨论】:

      【解决方案3】:

      我假设您需要在表中查询除主键之外的字段。您可以使用:

      Products_description::where('productid',$productId)->first()
      

      如果你说的是外键,那么你应该像这样在模型中定义它们:

      return $this->hasOne('App\Phone', 'foreign_key');
      

      以下是相关文档: https://laravel.com/docs/5.1/eloquent-relationships#one-to-one

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 1970-01-01
        • 2018-11-11
        • 2015-04-28
        • 2014-03-12
        • 2013-07-19
        • 1970-01-01
        • 2020-09-09
        • 2015-02-09
        相关资源
        最近更新 更多