【问题标题】:How to use substring with laravel eloquent?如何在 laravel eloquent 中使用子字符串?
【发布时间】:2018-11-07 10:39:17
【问题描述】:

我有2个相关表问题是在一个带来每个用户的客户,但客户代码主要基于4位,问题是有很多用户超过4位8或9这代表了你在公司的任务。但是我只需要带我需要与表建立关系的前4个,并且只能带公司名称

我正在像这样在 sql 中处理substring

$client = DB::connection('dpnmwin')->table('nmtrabajador')->select('SUBSTRING'('COD_UND', 1, 4))->where('CONDICION', '=', 'A')->get()

但这标志着我来自同一个代码编辑器的错误。

如何使用子字符串或其他方式做到这一点?

模范员工

class Employee extends Model
{
    protected $connection = 'dpnmwin';

    protected $table = 'nmtrabajador';

    protected $primaryKey = 'CODIGO';

    public function client(){

        return $this->belongsTo('App\Client', 'COD_UND');

    }

    public function position(){

        return $this->belongsTo('App\Position', 'COD_CARGO');

    }

}

模型客户端

class Client extends Model
{
    protected $connection = 'dpnmwin';

    protected $table = 'nmundfunc';

    protected $primaryKey = 'CEN_CODIGO';

    public function employee(){

        return $this->hasMany('App\Employee');

    }

}

文件列表.blade.php

 @foreach ($users as $user)
       <tr>
           <td>{{$user->CEDULA}}</td>
           <td>{{$user->NOMBRE}}</td>
           <td>{{$user->APELLIDO}}</td>
           <td>{{$user->EMAIL}}</td>
           <td>{{$user->position->CAR_DESCRI}}</td>
           <td>{{$user->client->CEN_DESCRI}}</td>
           <td><a href="{{ route('detailUser', ['user_id' => $user->CODIGO]) }}"><i class="fas fa-user"></i></a></td>
      </tr>
 @endforeach

【问题讨论】:

    标签: php sql laravel laravel-5


    【解决方案1】:

    \DB::raw() 用于select

    $client = DB::connection('dpnmwin')->
              table('nmtrabajador')->
              select(\DB::raw('SUBSTRING(COD_UND, 1, 4) as COD_UND'))->
              where('CONDICION', '=', 'A')->
              get()
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2017-10-06
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多