【问题标题】:Mapping field name in model using laravel使用 laravel 映射模型中的字段名称
【发布时间】:2015-05-03 02:28:09
【问题描述】:

有没有办法将数据库中的字段名称映射到模型中的不同属性名称?例如,如果数据库的字段名称为 customer_id 但我想以这种方式使用 eloquent Customer::get(['id']) 我尝试使用 getAttribute 方法,但在 eloquent 尝试获取值之后调用该方法。

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以使用访问器来处理此类属性,但无法使用 core eloquent 以这种方式查询它们。

    但不要害怕!使用这个包https://github.com/jarektkaczyk/eloquence,你可以轻松实现你想要的(特别是Mappable):

    // Customer model
    protected $maps =[
      'id' => 'customer_id',
      'name' => 'customer_name',
      ...
    ];
    
    // then you can do this:
    $customer = Customer::where('name', 'whatever')->first();
    // calls WHERE customer_name = ? sql
    
    $customer->id; // customer_id column
    $customer->name; // customer_name column
    $customer->name = 'different name'; // set mutator works as well
    

    它正在大力开发中,目前尚不支持select,但这只是一两天的事情。已经推送了select 支持。 p>

    【讨论】:

    • 我们也可以将 Mappable 用于关系吗?
    • 在你的模型中不要忘记使用 Sofa\Eloquence\Eloquence; //base trait use Sofa\Eloquence\Mappable; // 扩展 trait 然后在你的类中使用 Eloquence,Mappable;这个包超级棒!节省大量时间..
    猜你喜欢
    • 2022-08-03
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2019-10-27
    • 2013-11-22
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多