Mapping field name in model using laravel

前端 未结 1 514
抹茶落季
抹茶落季 2021-02-06 08:05

Is there a way to map field names to a database to a different attribute name in the model? For example, if the database has a field name of customer_id but I wante

相关标签:
1条回答
  • 2021-02-06 08:24

    You can use accessors to work with such attributes, but there's no way to query them this way with core eloquent.

    But fear not! Use this package https://github.com/jarektkaczyk/eloquence and you can easily achieve what you want (Mappable in particular):

    // 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
    

    It's in heavy development and currently select is not yet supported, but it's matter of day or two. select support has been pushed already.

    0 讨论(0)
提交回复
热议问题