【问题标题】:customize field name to be used on find method in laravel自定义要在 laravel 中的 find 方法上使用的字段名称
【发布时间】:2012-11-07 00:59:23
【问题描述】:

有没有办法自定义laravel中find方法使用的字段名:

User::find(1) //this assumes that the primary key field is always named id

我尝试在模型上这样做:

public static $id = 'user_id';

但这不起作用。它在执行 find() 时使用的查询仍在使用“id”列

我总是可以这样做:

$user = User::where('user_id', '=', 2);

但我喜欢输入更少的代码,我特别想将它链接起来以将新记录插入另一个表,但这不起作用:

$user = User::where('insect_id', '=', 2)->transactions()->insert(array('trans_id' => 34));

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    更新::(2013 年 11 月 11 日)

    从 laravel 4 开始,primaryKey 需要被覆盖才能访问主键属性。

    reference

    例子:

    受保护的 $primaryKey = 'user_id';

    旧::

    使用

    public static $key = 'user_id';
    

    在你的模型中

    详情请见http://laravel.com/api/source-class-Laravel.Database.Eloquent.Model.html#45...

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2012-06-23
      • 2017-03-15
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多