Laravel 查询如何排除某些字段?如只排除 content 文本,其它字段都需要。

ORM 查询如何排除某些字段?如只排除 content 文本,其它字段都需要。

$data = Content::where('pid',1)->get(['id','title','time', ...]);

这么写感觉很笨,有没有直接排除 content 字段,其它字段都要查询的方法呢?

在网上就找到了这些资料,找了老半天还是没有如意的,最后还是自己写吧,先贴代码:

这个是写在 model 里面的

    use Illuminate\Support\Facades\Schema;
    /**
     * 查询时去掉不必要的字段
     * $filed 可以为一个字符串就是一个字段,
     */
    public function field($filed)
    {
        $columns = Schema::getColumnListing($this->table);
        foreach ($columns as $key => $val)
        {
            if(is_array($filed)){
                if(in_array($val , $filed)) unset($columns[$key]);
            }else {
                if($val == $filed) unset($columns[$key]);
            }
        }
        return $columns;
    }

这个里面的 $filed 可以传单个字段也可传多个字段,一个字段。如: 

/***我这个是直接在控制器里面写的*/

    $ActivityModel = new Activity();//这一行就不多解释了吧


    $field = $ActivityModel->field('content');这个则是调用

多个字段:如

$ActivityModel = new Activity();

$field = $ActivityModel->field(['content','title']);

 这么写应该很清晰了吧

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值